class Solution:
def maxIceCream(self, costs, coins):
costs.sort()
count = 0
for price in costs:
if coins >= price:
coins -= price
count += 1
else:
break
return count
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
sort(costs.begin(), costs.end());
int count = 0;
for (int price : costs) {
if (coins >= price) {
coins -= price;
count++;
} else {
break;
}
}
return count;
}
};
class Solution {
public int maxIceCream(int[] costs, int coins) {
Arrays.sort(costs);
int count = 0;
for (int price : costs) {
if (coins >= price) {
coins -= price;
count++;
} else {
break;
}
}
return count;
}
}
var maxIceCream = function(costs, coins) {
costs.sort((a, b) => a - b);
let count = 0;
for (let price of costs) {
if (coins >= price) {
coins -= price;
count++;
} else {
break;
}
}
return count;
};
You are given an array costs
where each element represents the price of an ice cream bar, and an integer coins
representing the total amount of money you have. Your task is to buy as many ice cream bars as possible using the coins you have. Each ice cream bar can be purchased at most once, and you cannot spend more coins than you possess. Return the maximum number of ice cream bars you can buy.
At first glance, you might think about trying every possible combination of ice cream bars to see which set gives you the most bars without exceeding your coin limit. However, this brute-force approach is very inefficient, especially as the number of ice cream bars grows.
To optimize, consider what will let you buy the most bars: buying the cheapest ones first. If you always pick the least expensive bars, you'll be able to buy more before running out of coins. This leads to a greedy approach: sort the prices from lowest to highest, and keep buying until you can't afford the next one.
costs
array in ascending order. This lets you access the cheapest ice cream bars first.count
) to keep track of how many bars you have bought.costs
array:coins
to buy it.coins
and increment your counter.This greedy approach works because buying cheaper bars first always leaves you with more coins to potentially buy more bars, maximizing the count.
Suppose costs = [1, 3, 2, 4, 1]
and coins = 7
.
costs
: [1, 1, 2, 3, 4]coins = 7
and count = 0
.The final answer is 4, since you can buy 4 ice cream bars with 7 coins.
n
.costs
array takes O(n log n) time.The key insight is to always buy the cheapest available ice cream bars first. By sorting the prices and purchasing in order, you maximize the number of bars you can buy with your coins. This greedy approach is simple, efficient, and easy to implement, making it an elegant solution to the problem.