[LeetCode] Maximum Number of Eaten Apples

1705. Maximum Number of Eaten Apples

There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.

You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.

Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int eatenApples(vector<int>& apples, vector<int>& days) {
int res(0);
priority_queue<pair<int, int>> pq;
for(int i = 0; i < apples.size() or !pq.empty(); i++) {
if(i < apples.size() and apples[i]) pq.push({-i + -days[i], apples[i]});

while(!pq.empty() and (!pq.top().second or pq.top().first == -i)) pq.pop();

if(!pq.empty()) {
auto p = pq.top();
pq.pop();
if(p.second != 1)
pq.push({p.first, p.second - 1});
res++;
}

}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/08/PS/LeetCode/maximum-number-of-eaten-apples/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.