-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMaximum Number of Eaten Apples.java
38 lines (35 loc) · 1.18 KB
/
Maximum Number of Eaten Apples.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Runtime: 33 ms (Top 95.27%) | Memory: 45.90 MB (Top 56.76%)
class Solution {
class Basket{
int appleCount;
int day;
Basket(int appleCount, int day){
this.appleCount = appleCount;
this.day = day;
}
}
public int eatenApples(int[] apples, int[] days) {
int n = apples.length;
PriorityQueue<Basket> q = new PriorityQueue<>(n,(b1,b2) -> b1.day-b2.day);
int i; // counter for day
int apple = 0; // count of consumed apple
for(i=0; i<n; i++){
while(q.peek()!=null && (q.peek().appleCount < 1 || q.peek().day < i+1)){
q.poll();
}
if(apples[i] != 0 && days[i] !=0){
q.add(new Basket(apples[i], i+days[i]));
}
if(q.peek()==null) continue;
q.peek().appleCount--;
apple++;
}
while(q.peek() != null){
Basket basket = q.poll();
if(basket.day < i) continue;
apple += Math.min(basket.appleCount, basket.day-i);
i += Math.min(basket.appleCount, basket.day-i);
}
return apple;
}
}