Maximum Ice Cream Bars (LeetCode 1833): Solution and Explanation
You have coins coins and a list of ice cream bar prices. Buy bars in any order and return the largest number you can afford. The problem asks for a counting sort solution, which works because prices are at most 100,000.
Intuition
To maximize how many bars you buy, every coin should go as far as possible, so you always want the cheapest bar that is still on the shelf. If you ever bought a pricier bar while a cheaper one was left, swapping them would cost less and leave the count the same, so cheapest first is never worse.
That means the answer is the length of the longest prefix of the sorted prices whose sum fits in coins. Sorting with comparisons costs O(n log n). But prices are small whole numbers bounded by 100,000, so you can bucket them: count[p] is how many bars cost exactly p.
Walking the buckets from price 1 upward visits the bars in sorted order without ever sorting them. At price p you can afford coins // p bars, so you take min(count[p], coins // p) of them and pay for them all at once.
The moment you cannot take every bar in a bucket, you are done: the leftover coins are less than p, and every later bucket is even more expensive.
Approach: Counting sort plus greedy
- Create
countwith one slot per price up tomax(costs)and add 1 tocount[c]for each cost. - Set
bars = 0and walkpricefrom 1 to the largest cost, skipping empty buckets. - Compute
take = min(count[price], coins // price), add it tobars, and subtracttake * pricefromcoins. - If
take < count[price], stop, because no later price is affordable either. - Return
bars.
Step-by-step example
costs = [1,3,2,4,1], coins = 7
- Buckets: count[1] = 2, count[2] = 1, count[3] = 1, count[4] = 1.
- Price 1: 7 coins buy 7, so take min(2, 7) = 2. bars = 2, coins = 5.
- Price 2: take min(1, 2) = 1. bars = 3, coins = 3.
- Price 3: take min(1, 1) = 1. bars = 4, coins = 0.
- Price 4: 0 coins buy none, take = 0 < 1, so stop. The answer is 4.
Code: Python, Java, C++
1class Solution:
2 def maxIceCream(self, costs: List[int], coins: int) -> int:
3 count = [0] * (max(costs) + 1)
4 for c in costs:
5 count[c] += 1
6 bars = 0
7 for price in range(1, len(count)):
8 if count[price] == 0:
9 continue
10 take = min(count[price], coins // price)
11 bars += take
12 coins -= take * price
13 if take < count[price]:
14 break
15 return bars1class Solution {
2 public int maxIceCream(int[] costs, int coins) {
3 int maxCost = 0;
4 for (int c : costs) maxCost = Math.max(maxCost, c);
5 int[] count = new int[maxCost + 1];
6 for (int c : costs) {
7 count[c]++;
8 }
9 int bars = 0;
10 for (int price = 1; price <= maxCost; price++) {
11 if (count[price] == 0) {
12 continue;
13 }
14 int take = Math.min(count[price], coins / price);
15 bars += take;
16 coins -= take * price;
17 if (take < count[price]) {
18 break;
19 }
20 }
21 return bars;
22 }
23}1class Solution {
2public:
3 int maxIceCream(vector<int>& costs, int coins) {
4 int maxCost = *max_element(costs.begin(), costs.end());
5 vector<int> count(maxCost + 1, 0);
6 for (int c : costs) {
7 count[c]++;
8 }
9 int bars = 0;
10 for (int price = 1; price <= maxCost; price++) {
11 if (count[price] == 0) {
12 continue;
13 }
14 int take = min(count[price], coins / price);
15 bars += take;
16 coins -= take * price;
17 if (take < count[price]) {
18 break;
19 }
20 }
21 return bars;
22 }
23};Time and space complexity
O(n + m)
Filling the buckets takes O(n), and the sweep visits at most m prices, where m is the largest cost.
O(m)
The count array has one slot per possible price up to the maximum cost.
Other approaches
Sort and take a prefix (time O(n log n), space O(1) to O(n) depending on the sort)
Sort costs and add prices from the smallest until the next one does not fit. It is short and correct, but it uses a comparison sort, which the problem asks you to avoid.
Min-heap (time O(n + k log n), space O(n))
Heapify the costs and pop the cheapest while it fits. It can stop early after k pops, giving O(n + k log n), but it is no better than counting here.
Common mistakes
- Taking one bar at a time inside the bucket loop. With up to 100,000 bars at one price that still works, but
min(count, coins // price)handles a whole bucket in one step. - Continuing the sweep after a partial bucket. Leftover coins are below the current price, so later buckets can never be afforded.
- Sizing the count array by
ninstead of by the largest cost. - Overflow when computing totals in languages with 32-bit ints.
take * pricenever exceedscoins, so it stays in range, but summing all costs up front can overflow.
Frequently asked questions
Why is buying the cheapest bars first optimal?
If a solution bought a bar while a cheaper one was left unbought, swapping the two keeps the number of bars the same and spends fewer coins. Repeating the swap turns any optimal purchase into the cheapest-first one.
Why does the problem ask for counting sort?
Prices are integers in a small fixed range, so counting them sorts in linear time. It is the textbook case where counting sort beats comparison sorting.
Why stop at the first bucket you cannot finish?
After taking as many bars as possible at price p, fewer than p coins remain. Every later bucket costs more than p, so nothing else can be bought.
What is the time complexity?
O(n + m) time and O(m) space, where m is the largest cost (at most 100,000).