It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
Note: The boy can buy the ice cream bars in any order.
Return the maximum number of ice cream bars the boy can buy with coins coins.
You must solve the problem by counting sort.
Example 1:
Input: costs = [1,3,2,4,1], coins = 7 Output: 4 Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
Example 2:
Input: costs = [10,6,8,7,7,8], coins = 5 Output: 0 Explanation: The boy cannot afford any of the ice cream bars.
Example 3:
Input: costs = [1,6,3,1,2,5], coins = 20 Output: 6 Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
Constraints:
costs.length == n1 <= n <= 1051 <= costs[i] <= 1051 <= coins <= 108This approach involves sorting the array of costs to ensure the boy buys the cheapest available ice cream bars first. After sorting, iterate through the list and keep buying bars until you run out of coins.
Steps involve:
This C program sorts the costs array using qsort and calculates the maximum number of ice creams that can be bought while iterating through the sorted array. It returns the count of ice creams the boy can afford.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1), as no additional space is required beyond the input.
This solution uses a variation of counting sort suitable for this specific problem due to the constraint that costs[i] <= 100,000.
Steps involve:
This Python solution uses a frequency array to store the number of each cost. By iterating over these costs in order (with known max cost), it calculates how many bars of each cost can be purchased and subtracts the respective cost from the available coins, tallying the total ice creams bought.
Time Complexity: O(n + max(costs)), where max(costs) could be up to 100,000.
Space Complexity: O(max(costs)), because of the frequency array used.
| Approach | Complexity |
|---|---|
| Approach 1: Greedy Algorithm using Sorting | Time Complexity: O(n log n) due to the sorting step. |
| Approach 2: Counting Sort Optimization | Time Complexity: O(n + max(costs)), where max(costs) could be up to 100,000. |
Leetcode# 1833. Maximum Ice Cream Bars || Code + Explanation + Example Walkthrough • Code with Alisha • 2,634 views views
Watch 9 more video solutions →Practice Maximum Ice Cream Bars with our built-in code editor and test cases.
Practice on FleetCode