LeetCode 1833: Maximum Ice Cream Bars – Java Greedy & Counting Sort Solution Explained

Learn Greedy Algorithms, Counting Sort Optimization, Dry Runs, Complexity Analysis, and Interview Strategies Through This Classic Budget Allocation Problem

Krishna Shrivastava
1 views
LinkedInGithubX
0
0
LeetCode 1833: Maximum Ice Cream Bars – Java Greedy & Counting Sort Solution Explained
Listen to articleAudio version
Ad

LeetCode 1833: Maximum Ice Cream Bars – Java Greedy Solution Explained

Buy the Maximum Number of Ice Cream Bars Using Sorting and Greedy Strategy

Introduction

LeetCode 1833, Maximum Ice Cream Bars, is a classic Greedy Algorithm problem that teaches an important optimization principle:

When you want to maximize the number of items purchased with a limited budget, always buy the cheapest items first.

Although the problem statement specifically mentions solving it using Counting Sort, understanding the Greedy approach first helps build intuition before moving to the optimized counting-sort solution.

In this article, we'll cover:

  1. Problem intuition
  2. Greedy strategy
  3. Sorting-based solution
  4. Counting Sort optimization
  5. Dry run examples
  6. Complexity analysis
  7. Interview insights

Problem Statement

Problem Link -: Maximum Ice Cream Bars

A boy has a fixed number of coins.

You are given:

costs[i]

which represents the price of the ith ice cream bar.

The boy can purchase ice cream bars in any order.

Your task is to determine the maximum number of ice cream bars that can be bought without exceeding the available coins.

Example 1

Input

costs = [1,3,2,4,1]
coins = 7

Output

4

Explanation

Sort the costs:

[1,1,2,3,4]

Buy in order:

1 → remaining 6
1 → remaining 5
2 → remaining 3
3 → remaining 0

Total bars purchased:

4

Example 2

Input

costs = [10,6,8,7,7,8]
coins = 5

Output

0

Even the cheapest ice cream costs more than the available coins.

Example 3

Input

costs = [1,6,3,1,2,5]
coins = 20

Output

6

The boy can purchase every ice cream bar.

Key Observation

Suppose you have:

Coins = 10

and:

Costs = [1,2,8]

Buying:

8 first

allows only:

8 + 1 = 9

Total bars:

2

But buying cheapest first:

1 + 2 + 8 = 11

Not possible.

Try:

1 + 2 = 3

Still leaves room for more purchases in many cases.

To maximize quantity:

Always buy the cheapest available ice cream first.

This immediately suggests a Greedy strategy.

Approach 1: Sorting + Greedy

Steps

  1. Sort the array.
  2. Buy ice creams from cheapest to most expensive.
  3. Stop when coins run out.
  4. Return the count.

Java Solution

class Solution {

public int maxIceCream(int[] costs, int coins) {

Arrays.sort(costs);

int count = 0;

for (int cost : costs) {

if (coins >= cost) {

coins -= cost;
count++;
}
}

return count;
}
}

Dry Run

Input

costs = [1,3,2,4,1]
coins = 7

After Sorting

[1,1,2,3,4]

Purchase Process

Buy first:

coins = 7 - 1 = 6
count = 1

Buy second:

coins = 6 - 1 = 5
count = 2

Buy third:

coins = 5 - 2 = 3
count = 3

Buy fourth:

coins = 3 - 3 = 0
count = 4

Cannot buy:

4

Final answer:

4

Why Greedy Works

The goal is:

Maximize quantity

not:

Maximize money spent

Choosing a more expensive ice cream earlier can only reduce the number of future purchases.

Therefore:

Picking the cheapest available option is always optimal.

This makes Greedy the correct strategy.

Follow-Up: Counting Sort Solution

The problem explicitly asks:

You must solve it using Counting Sort.

Why?

Because:

1 <= costs[i] <= 100000

The cost values have a bounded range.

Instead of sorting:

O(n log n)

we can count frequencies.

Counting Sort Approach

Step 1

Create frequency array.

int[] freq = new int[100001];

Step 2

Count occurrences.

for (int cost : costs) {
freq[cost]++;
}

Step 3

Process costs from smallest to largest.

for (int price = 1; price <= 100000; price++) {
while (freq[price] > 0 && coins >= price) {
coins -= price;
freq[price]--;
count++;
}
}

Optimized Counting Sort Solution

class Solution {

public int maxIceCream(int[] costs, int coins) {

int[] freq = new int[100001];

for (int cost : costs) {
freq[cost]++;
}

int count = 0;

for (int price = 1; price <= 100000; price++) {

while (freq[price] > 0 && coins >= price) {

coins -= price;
freq[price]--;
count++;
}
}

return count;
}
}

Complexity Analysis

Sorting Solution

Time Complexity

O(n log n)

Space Complexity

O(1)

(ignoring sorting implementation details)

Counting Sort Solution

Time Complexity

O(n + 100000)

Effectively linear.

Space Complexity

O(100000)

for the frequency array.

Which Solution Should You Use?

ApproachTimeSpace
Sorting + GreedyO(n log n)O(1)
Counting SortO(n + 100000)O(100000)

For interviews:

  1. Explain the Greedy idea first.
  2. Mention Sorting solution.
  3. Then discuss Counting Sort because the problem explicitly requires it.

This demonstrates both problem-solving ability and optimization awareness.

Common Mistakes

Mistake 1

Buying expensive bars first.

Reduces total quantity purchased.

Mistake 2

Stopping after a single unaffordable item in an unsorted array.

Always sort or process costs in increasing order.

Mistake 3

Ignoring the Counting Sort requirement.

The online judge may accept sorting, but interviewers may specifically ask for the linear-time optimization.

Key Takeaways

  1. The problem is based on Greedy selection.
  2. To maximize purchases, buy the cheapest items first.
  3. Sorting provides a simple solution.
  4. Counting Sort satisfies the problem's follow-up requirement.
  5. Greedy works because every expensive purchase reduces future buying power.
  6. Counting Sort improves performance when value ranges are bounded.

Conclusion

LeetCode 1833: Maximum Ice Cream Bars is an excellent Greedy Algorithm problem that demonstrates how local optimal choices can lead to a globally optimal solution.

The sorting-based approach is intuitive and easy to implement, while the counting-sort optimization leverages the bounded range of costs to achieve near-linear performance.

Understanding both approaches prepares you not only for coding interviews but also for real-world optimization problems involving budgets, resources, and constrained selections.

Ai Assistant Kas