
LeetCode 1833: Maximum Ice Cream Bars – Java Greedy & Counting Sort Solution Explained
LeetCode 1833: Maximum Ice Cream Bars – Java Greedy Solution ExplainedBuy the Maximum Number of Ice Cream Bars Using Sorting and Greedy StrategyIntroductionLeetCode 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:Problem intuitionGreedy strategySorting-based solutionCounting Sort optimizationDry run examplesComplexity analysisInterview insightsProblem StatementProblem Link -: Maximum Ice Cream BarsA 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 1Inputcosts = [1,3,2,4,1]coins = 7Output4ExplanationSort the costs:[1,1,2,3,4]Buy in order:1 → remaining 61 → remaining 52 → remaining 33 → remaining 0Total bars purchased:4Example 2Inputcosts = [10,6,8,7,7,8]coins = 5Output0Even the cheapest ice cream costs more than the available coins.Example 3Inputcosts = [1,6,3,1,2,5]coins = 20Output6The boy can purchase every ice cream bar.Key ObservationSuppose you have:Coins = 10and:Costs = [1,2,8]Buying:8 firstallows only:8 + 1 = 9Total bars:2But buying cheapest first:1 + 2 + 8 = 11Not possible.Try:1 + 2 = 3Still 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 + GreedyStepsSort the array.Buy ice creams from cheapest to most expensive.Stop when coins run out.Return the count.Java Solutionclass 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 RunInputcosts = [1,3,2,4,1]coins = 7After Sorting[1,1,2,3,4]Purchase ProcessBuy first:coins = 7 - 1 = 6count = 1Buy second:coins = 6 - 1 = 5count = 2Buy third:coins = 5 - 2 = 3count = 3Buy fourth:coins = 3 - 3 = 0count = 4Cannot buy:4Final answer:4Why Greedy WorksThe goal is:Maximize quantitynot:Maximize money spentChoosing 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 SolutionThe problem explicitly asks:You must solve it using Counting Sort.Why?Because:1 <= costs[i] <= 100000The cost values have a bounded range.Instead of sorting:O(n log n)we can count frequencies.Counting Sort ApproachStep 1Create frequency array.int[] freq = new int[100001];Step 2Count occurrences.for (int cost : costs) { freq[cost]++;}Step 3Process 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 Solutionclass 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 AnalysisSorting SolutionTime ComplexityO(n log n)Space ComplexityO(1)(ignoring sorting implementation details)Counting Sort SolutionTime ComplexityO(n + 100000)Effectively linear.Space ComplexityO(100000)for the frequency array.Which Solution Should You Use?ApproachTimeSpaceSorting + GreedyO(n log n)O(1)Counting SortO(n + 100000)O(100000)For interviews:Explain the Greedy idea first.Mention Sorting solution.Then discuss Counting Sort because the problem explicitly requires it.This demonstrates both problem-solving ability and optimization awareness.Common MistakesMistake 1Buying expensive bars first.Reduces total quantity purchased.Mistake 2Stopping after a single unaffordable item in an unsorted array.Always sort or process costs in increasing order.Mistake 3Ignoring the Counting Sort requirement.The online judge may accept sorting, but interviewers may specifically ask for the linear-time optimization.Key TakeawaysThe problem is based on Greedy selection.To maximize purchases, buy the cheapest items first.Sorting provides a simple solution.Counting Sort satisfies the problem's follow-up requirement.Greedy works because every expensive purchase reduces future buying power.Counting Sort improves performance when value ranges are bounded.ConclusionLeetCode 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.










