class Solution {
public int maxIceCream(int[] costs, int coins) {
// Maximum possible cost is 100000
int[] freq = new int[100001];
// Count frequencies
for (int cost : costs) {
freq[cost]++;
}
int ans = 0;
// Buy cheapest ice creams first
for (int cost = 1; cost <= 100000; cost++) {
if (freq[cost] == 0) continue;
int canBuy = Math.min(freq[cost], coins / cost);
ans += canBuy;
coins -= canBuy * cost;
if (coins < cost) {
// Can't afford any more at this cost or higher
continue;
}
}
return ans;
}
}
class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
# Maximum possible cost is 100000
freq = [0] * 100001
# Count frequencies
for cost in costs:
freq[cost] += 1
ans = 0
# Buy cheapest ice creams first
for cost in range(1, 100001):
if freq[cost] == 0:
continue
canBuy = min(freq[cost], coins // cost)
ans += canBuy
coins -= canBuy * cost
if coins < cost:
continue
return ans
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
// Maximum possible cost is 100000
vector<int> freq(100001, 0);
// Count frequencies
for (int cost : costs) {
freq[cost]++;
}
int ans = 0;
// Buy cheapest ice creams first
for (int cost = 1; cost <= 100000; cost++) {
if (freq[cost] == 0) continue;
int canBuy = min(freq[cost], coins / cost);
ans += canBuy;
coins -= canBuy * cost;
if (coins < cost) {
continue;
}
}
return ans;
}
};
/**
* @param {number[]} costs
* @param {number} coins
* @return {number}
*/
var maxIceCream = function(costs, coins) {
// Maximum possible cost is 100000
const freq = new Array(100001).fill(0);
// Count frequencies
for (const cost of costs) {
freq[cost]++;
}
let ans = 0;
// Buy cheapest ice creams first
for (let cost = 1; cost <= 100000; cost++) {
if (freq[cost] === 0) continue;
const canBuy = Math.min(freq[cost], Math.floor(coins / cost));
ans += canBuy;
coins -= canBuy * cost;
if (coins < cost) {
continue;
}
}
return ans;
};