Sponsored
Sponsored
This 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:
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1), as no additional space is required beyond the input.
1function maxIceCream(costs, coins) {
2 costs.sort((a, b) => a - b);
3 let count = 0;
4 for (let cost of costs) {
5 if (coins >= cost) {
6 coins -= cost;
7 count++;
8 } else {
9 break;
10 }
11 }
12 return count;
13}
14
15console.log(maxIceCream([1, 3, 2, 4, 1], 7));
This JavaScript code sorts the array of costs using a comparator and iteratively checks each cost to determine how many ice cream bars can be purchased within the coin limit. It counts and stops if a cost is beyond the current coins.
This solution uses a variation of counting sort suitable for this specific problem due to the constraint that costs[i] <= 100,000.
Steps involve:
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.
1def maxIceCream(costs, coins):
2 max_cost = max(costs)
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.