/**
* Problem: LeetCode 1833 - Maximum Ice Cream Bars
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
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;
}
}
"""
Problem: LeetCode 1833 - Maximum Ice Cream Bars
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
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
can_buy = min(freq[cost], coins // cost)
ans += can_buy
coins -= can_buy * cost
if coins < cost:
# Can't afford any more at this cost or higher
continue
return ans
/**
* Problem: LeetCode 1833 - Maximum Ice Cream Bars
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
using namespace std;
/**
* Problem: LeetCode 1833 - Maximum Ice Cream Bars
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
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) {
// Can't afford any more at this cost or higher
continue;
}
}
return ans;
}
};
/**
* Problem: LeetCode 1833 - Maximum Ice Cream Bars
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var maxIceCream = function(costs, coins) {
// Maximum possible cost is 100000
const freq = new Int32Array(100001);
// 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) {
// Can't afford any more at this cost or higher
continue;
}
}
return ans;
};