Leetcode 1705 吃苹果的最大数目

题目

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

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

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

解题思路

  贪心。对于每一天得选择最快过期的苹果,需要实时知道最快过期的苹果,最好用的就是优先队列。枚举每一天,将好的苹果入队,坏了的苹果出队,优先拿快过期的苹果,模拟整个吃的过程就是这个题的解。

代码
class Solution {
    public int eatenApples(int[] apples, int[] days) {
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[1] - b[1]);
        int length = apples.length, ans = 0;

        for (int i = 0; i < length || !queue.isEmpty(); i++) {
            if (i < length && apples[i] > 0) {
                queue.add(new int[]{apples[i], i + days[i] - 1});
            }
            while (!queue.isEmpty() && queue.peek()[1] < i) queue.poll();
            if (!queue.isEmpty()) {
                int[] now = queue.poll();
                now[0]--;
                ans++;
                if (now[0] > 0 && now[1] > i) queue.add(now);
            }
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值