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.
1def maxIceCream(costs, coins):
2 costs.sort()
3 count = 0
4 for cost in costs:
5 if coins >= cost:
6 coins -= cost
7 count += 1
8 else:
9 break
10 return count
11
12print(maxIceCream([1, 3, 2, 4, 1], 7))
This Python function sorts the given costs list and iteratively deducts the cost of each purchasable ice cream bar from the available coins. The process stops when no more bars can be bought, and the count is returned.
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.