Maximum Number of Eaten Apples LeetCode solution in Java

1
class Solution {
2
class Basket {
3
int appleCount;
4
int day;
5

6
Basket(int appleCount, int day) {
7
this.appleCount = appleCount;
8
this.day = day;
9
}
10
}
11

12
public int eatenApples(int[] apples, int[] days) {
13
int n = apples.length;
14
PriorityQueue<Basket> q = new PriorityQueue<>(n, (b1, b2) -> b1.day - b2.day);
15
int i; // counter for day
16
int apple = 0; // count of consumed apple
17

18
for (i = 0; i < n; i++) {
19
while (q.peek() != null && (q.peek().appleCount < 1 || q.peek().day < i + 1)) {
20
q.poll();
21
}
22
if (apples[i] != 0 && days[i] != 0) {
23
q.add(new Basket(apples[i], i + days[i]));
24
}
25
if (q.peek() == null) continue;
26
q.peek().appleCount--;
27
apple++;
28
}
29

30
while (q.peek() != null) {
31
Basket basket = q.poll();
32
if (basket.day < i) continue;
33
apple += Math.min(basket.appleCount, basket.day - i);
34
i += Math.min(basket.appleCount, basket.day - i);
35
}
36
return apple;
37
}
38
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0