力扣 1833. 雪糕的最大数量(题解)

题目

夏日炎炎,小男孩 Tony 想买一些雪糕消消暑。
商店中新到 n 支雪糕,用长度为 n 的数组 costs 表示雪糕的定价,其中 costs[i] 表示第 i 支雪糕的现金价格。Tony 一共有 coins 现金可以用于消费,他想要买尽可能多的雪糕。
给你价格数组 costs 和现金量 coins ,请你计算并返回 Tony 用 coins 现金能够买到的雪糕的 最大数量 。
注意:Tony 可以按任意顺序购买雪糕。

示例 1:输入:costs = [1,3,2,4,1], coins = 7;输出:4
解释:Tony 可以买下标为 0、1、2、4 的雪糕,总价为 1 + 3 + 2 + 1 = 7
示例 2:输入:costs = [10,6,8,7,7,8], coins = 5;输出:0
解释:Tony 没有足够的钱买任何一支雪糕。
示例 3:输入:costs = [1,6,3,1,2,5], coins = 20;输出:6
解释:Tony 可以买下所有的雪糕,总价为 1 + 6 + 3 + 1 + 2 + 5 = 18 。

提示:

  • costs.length == n
  • 1 <= n <= 105
  • 1 <= costs[i] <= 105
  • 1 <= coins <= 108

题解

本题只追求购买雪糕的最大数量,因此自然是先买最便宜的,所以可以使用贪心算法,数组排好序后,从便宜的开始买。

class Solution {
    public int maxIceCream(int[] costs, int coins) {
        // Arrays.sort(costs);
        quickSort(costs, 0, costs.length - 1);
        int count = 0;
        for(int i = 0; i < costs.length; i++){
            if(coins >= costs[i]){
                coins -= costs[i];
                count++;
            }else break;
        }
        return count;
    }

    // 复习快速排序算法
    private void quickSort(int[] nums, int l, int r){
        if(l >= r) return;
        int tmp = nums[l];  // 设置基准数
        int i = l;
        int j = r;
        while(i < j){
            while(i < j && nums[j] > tmp) j--;  //右标移动
            if(i < j) nums[i++] = nums[j];   // 赋值后,说明当前nums[i]<=tmp,因此不需要进入下轮判断,故i++
            while(i < j && nums[i] < tmp) i++;
            if(i < j) nums[j--] = nums[i];  // 同理
        }
        nums[i] = tmp;
        quickSort(nums, l, i - 1);
        quickSort(nums, i + 1, r);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值