Buy Two Chocolates

easy array greedy sorting

Problem

You have money units of cash and an array prices of chocolate prices. You must buy exactly two chocolates so that the leftover money stays non-negative, while minimizing the sum you pay. Return the leftover money after buying the cheapest affordable pair; if no pair is affordable, return money unchanged.

Inputprices = [1, 2, 2], money = 3
Output0
Cheapest two cost 1 + 2 = 3 ≤ 3, so leftover = 3 − 3 = 0.

def buyChoco(prices, money):
    min1 = min2 = float('inf')        # two cheapest prices so far
    for p in prices:
        if p < min1:                  # new cheapest: shift old min1 down
            min2 = min1
            min1 = p
        elif p < min2:                # new second cheapest
            min2 = p
    cost = min1 + min2                # cheapest pair total
    if cost <= money:                 # affordable -> spend it
        return money - cost
    return money                      # cannot afford any pair
function buyChoco(prices, money) {
  let min1 = Infinity, min2 = Infinity;   // two cheapest prices so far
  for (const p of prices) {
    if (p < min1) {                        // new cheapest: shift old min1 down
      min2 = min1;
      min1 = p;
    } else if (p < min2) {                 // new second cheapest
      min2 = p;
    }
  }
  const cost = min1 + min2;               // cheapest pair total
  if (cost <= money) return money - cost; // affordable -> spend it
  return money;                           // cannot afford any pair
}
int buyChoco(int[] prices, int money) {
    int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; // two cheapest
    for (int p : prices) {
        if (p < min1) {                    // new cheapest: shift old min1 down
            min2 = min1;
            min1 = p;
        } else if (p < min2) {             // new second cheapest
            min2 = p;
        }
    }
    int cost = min1 + min2;                // cheapest pair total
    if (cost <= money) return money - cost; // affordable -> spend it
    return money;                          // cannot afford any pair
}
int buyChoco(vector<int>& prices, int money) {
    int min1 = INT_MAX, min2 = INT_MAX;    // two cheapest prices so far
    for (int p : prices) {
        if (p < min1) {                     // new cheapest: shift old min1 down
            min2 = min1;
            min1 = p;
        } else if (p < min2) {              // new second cheapest
            min2 = p;
        }
    }
    int cost = min1 + min2;                // cheapest pair total
    if (cost <= money) return money - cost; // affordable -> spend it
    return money;                          // cannot afford any pair
}
Time: O(n) Space: O(1)