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.
1import java.util.Arrays;
2
3public class Solution {
4 public int maxIceCream(int[] costs, int coins) {
5 Arrays.sort(costs);
6 int count = 0;
7 for (int cost : costs) {
8 if (coins >= cost) {
9 coins -= cost;
10 count++;
11 } else {
12 break;
13 }
14 }
15 return count;
16 }
17
18 public static void main(String[] args) {
19 Solution sol = new Solution();
20 int[] costs = {1, 3, 2, 4, 1};
21 System.out.println(sol.maxIceCream(costs, 7));
22 }
23}
In this Java solution, Arrays.sort is used to reorder the costs array. A loop then iterates through each cost, subtracting it from coins as long as there are sufficient coins left. The number of ice creams bought 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.