Maximum Ice Cream Bars (LeetCode 1833): Solution and Explanation

Medium
Array
Greedy
Sorting
Counting sort

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

  1. Create count with one slot per price up to max(costs) and add 1 to count[c] for each cost.
  2. Set bars = 0 and walk price from 1 to the largest cost, skipping empty buckets.
  3. Compute take = min(count[price], coins // price), add it to bars, and subtract take * price from coins.
  4. If take < count[price], stop, because no later price is affordable either.
  5. Return bars.

Step-by-step example

costs = [1,3,2,4,1], coins = 7
  1. Buckets: count[1] = 2, count[2] = 1, count[3] = 1, count[4] = 1.
  2. Price 1: 7 coins buy 7, so take min(2, 7) = 2. bars = 2, coins = 5.
  3. Price 2: take min(1, 2) = 1. bars = 3, coins = 3.
  4. Price 3: take min(1, 1) = 1. bars = 4, coins = 0.
  5. 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 bars
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Counting sort plus greedy O(n + m)
Sort and take a prefix O(n log n)
Min-heap O(n + k log n)
Time

O(n + m)

Filling the buckets takes O(n), and the sweep visits at most m prices, where m is the largest cost.

Space

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 n instead of by the largest cost.
  • Overflow when computing totals in languages with 32-bit ints. take * price never exceeds coins, 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).