阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定雪糕价格数组 costs 和现金 coins,想要购买尽可能多的雪糕,优先买便宜的;要求使用计数排序思路解题,返回最多能购买的雪糕数量。
示例:
输入:costs = [1,3,2,4,1], coins = 7 输出:4 解释:依次购买价格1、1、2、3,总花费7,共4支。
package lc1800_lc1899.lc1833;
import java.util.Arrays;
class Solution {
public int maxIceCream(int[] costs, int coins) {
Arrays.sort(costs);
int cur=costs[0];
int index=0;
int count = 0;
while (coins>cur){
coins-=costs[index++];
count++;
}
return count;
}
}class Solution {
public int maxIceCream(int[] costs, int coins) {
// 计数数组,题目价格上限100000
int[] counts = new int[100001];
// 统计每种价格雪糕的数量
for (int cost : costs) {
counts[cost] ++;
}
int ans = 0;
// 从小到大遍历价格,贪心优先买低价雪糕
for (int i = 1; i < 100001; i++) {
// 连单支都买不起,直接退出
if (coins < i) {
return ans;
}
// 逐个购买当前价格全部雪糕
for (int j = 0; j < counts[i]; j++) {
coins -= i;
ans ++;
// 购买后剩余现金不足下一支,提前返回
if (coins < i) {
return ans;
}
}
}
return ans;
}
}