1705. 吃苹果的最大数目

题目

有一棵特殊的苹果树,一连 n 天,每天都可以长出若干个苹果。在第 i 天,树上会长出 apples[i] 个苹果,这些苹果将会在 days[i] 天后(也就是说,第 i + days[i] 天时)腐烂,变得无法食用。也可能有那么几天,树上不会长出新的苹果,此时用 apples[i] == 0 且 days[i] == 0 表示。

你打算每天 最多 吃一个苹果来保证营养均衡。注意,你可以在这 n 天之后继续吃苹果。

给你两个长度为 n 的整数数组 days 和 apples ,返回你可以吃掉的苹果的最大数目。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-number-of-eaten-apples
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。在这里插入图片描述

代码

class Solution {
    public int eatenApples(int[] apples, int[] days) {
        int n=apples.length,m= days.length;
        int maxday=-1,ans=0;
        PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {//{个数,保质期到第几天}
                return o1[1]-o2[1];
            }
        });
        for (int i = 0; i <n ; i++) {
            if (apples[i]>0){
                pq.offer(new int[]{apples[i],i+days[i]-1}); //存
            }
            while (!pq.isEmpty()){//不为空
                //找出保质期快到了的那个苹果,吃掉
                int[] apple=pq.peek();
                if (apple[1]<i) pq.poll();//已过期
                else{
                    ans++;
                    apple[0]--;
                    if (apple[0]==0) pq.poll();//已经吃光了
                    break;
                }
            }

        }
        //没有新苹果了
        int i=n;
        while (!pq.isEmpty()){//不为空
            //找出保质期快到了的那个苹果,吃掉
            int[] apple=pq.peek();
            if (apple[1]<i) pq.poll();//已过期
            else{
                ans++;
                apple[0]--;
                if (apple[0]==0) pq.poll();//已经吃光了
                i++;
            }
        }
        return ans;
    }
}

要点

  • 本题使用贪心,每次吃掉即将要过期的苹果
  • 为了快速找到即将过期的苹果,使用优先级队列来储存
  • 使用peek操作可以直接修改队列内的元素,而哈希map不能修改key
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值