题目
有一棵特殊的苹果树,一连 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;
}
}