LeetCode 1833. Maximum Ice Cream Bars

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
sort(begin(costs), end(costs));
int ans = 0;
for (int cost : costs) {
if ((coins -= cost) >= 0)
++ans;
else
break;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const int N = 100001;
int c[N];
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
memset(c, 0, sizeof c);
for (int cost : costs) ++c[cost];
int ans = 0;
for (int i = 1; i < N && i <= coins; ++i) {
if (c[i]) {
int x = min(c[i], coins / i);
coins -= i * x;
ans += x;
}
}
return ans;
}
};