Maximum Ice Cream Bars

medium array greedy sorting

Problem

You are given an array costs, where costs[i] is the price of the i-th ice cream bar, and an integer coins holding the money you have. Buy as many bars as possible — each bar can be bought at most once — and return the maximum number of bars you can afford.

Inputcosts = [1, 3, 2, 4, 1], coins = 7
Output4
Buy the bars priced 1, 1, 2, and 3 for a total of 7 coins — 4 bars. The bar priced 4 is no longer affordable.

def max_ice_cream(costs, coins):
    costs.sort()
    bought = 0
    for price in costs:
        if price > coins:
            break
        coins -= price
        bought += 1
    return bought
function maxIceCream(costs, coins) {
  costs.sort((a, b) => a - b);
  let bought = 0;
  for (const price of costs) {
    if (price > coins) break;
    coins -= price;
    bought += 1;
  }
  return bought;
}
class Solution {
    public int maxIceCream(int[] costs, int coins) {
        Arrays.sort(costs);
        int bought = 0;
        for (int price : costs) {
            if (price > coins) break;
            coins -= price;
            bought += 1;
        }
        return bought;
    }
}
int maxIceCream(vector<int>& costs, int coins) {
    sort(costs.begin(), costs.end());
    int bought = 0;
    for (int price : costs) {
        if (price > coins) break;
        coins -= price;
        bought += 1;
    }
    return bought;
}
Time: O(n log n) Space: O(1)