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