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 _themaximum number of ice cream bars the boy can buy with _coinscoins.
To maximize the number of ice cream bars, always buy the cheapest bars first. Since costs are bounded, we can use counting sort to efficiently count the number of bars at each price, then buy as many as possible from cheapest to most expensive until coins run out.
classSolution {
publicintmaxIceCream(int[] costs, int coins) {
int mx = 0;
for (int c : costs) mx = Math.max(mx, c);
int[] cnt =newint[mx + 1];
for (int c : costs) cnt[c]++;
int ans = 0;
for (int i = 1; i <= mx && coins > 0; ++i) {
int buy = Math.min(cnt[i], coins / i);
ans += buy;
coins -= buy * i;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funmaxIceCream(costs: IntArray, coins: Int): Int {
var mx = 0for (c in costs) mx = maxOf(mx, c)
val cnt = IntArray(mx + 1)
for (c in costs) cnt[c]++var ans = 0var coinsLeft = coins
for (i in1..mx) {
if (coinsLeft <=0) breakval buy = minOf(cnt[i], coinsLeft / i)
ans += buy
coinsLeft -= buy * i
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defmaxIceCream(self, costs: list[int], coins: int) -> int:
mx = max(costs)
cnt = [0] * (mx +1)
for c in costs:
cnt[c] +=1 ans =0for i in range(1, mx +1):
if coins <=0:
break buy = min(cnt[i], coins // i)
ans += buy
coins -= buy * i
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnmax_ice_cream(costs: Vec<i32>, coins: i32) -> i32 {
let mx =*costs.iter().max().unwrap();
letmut cnt =vec![0; (mx +1) asusize];
for&c in&costs {
cnt[c asusize] +=1;
}
letmut ans =0;
letmut coins = coins;
for i in1..=mx {
let buy = cnt[i asusize].min(coins / i);
ans += buy;
coins -= buy * i;
if coins <=0 { break; }
}
ans
}
}