Problem Description
Given an array of ice cream bar costs and a total number of coins, determine the maximum number of ice cream bars the boy can buy. The bars can be purchased in any order, and the solution must use counting sort to efficiently process the costs.
Key Insights
- Utilize counting sort since the cost values are within a known, limited range.
- Instead of sorting the entire array, count the frequency of each cost.
- Iterate over the costs starting from the smallest value, subtracting from the available coins and counting the number of bars that can be bought.
- Stop once the coins are exhausted or there are no further affordable bars.
Space and Time Complexity
Time Complexity: O(n + m), where n is the number of ice cream bars and m is the maximum cost value (since we iterate over the frequency array up to m). Space Complexity: O(m), to store the frequency counts for costs from 1 up to the maximum cost.
Solution
We use counting sort by creating an array (or hashmap) to count how many ice cream bars exist for each possible cost. Then, traversing the cost values in increasing order, we subtract the cumulative cost from the coins available and add to the count of bars bought. This greedy approach ensures that we always buy the cheapest available ice cream bars first, maximizing the total number purchased.