Skip to content

1833. Maximum Ice Cream Bars

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int maxIceCream(vector<int>& costs, int coins) {
    ranges::sort(costs);

    for (int i = 0; i < costs.size(); ++i)
      if (coins >= costs[i])
        coins -= costs[i];
      else
        return i;

    return costs.size();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int maxIceCream(int[] costs, int coins) {
    Arrays.sort(costs);

    for (int i = 0; i < costs.length; ++i)
      if (coins >= costs[i])
        coins -= costs[i];
      else
        return i;

    return costs.length;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def maxIceCream(self, costs: list[int], coins: int) -> int:
    for i, cost in enumerate(sorted(costs)):
      if coins >= cost:
        coins -= cost
      else:
        return i

    return len(costs)