Untitled
unknown
plain_text
9 months ago
1.5 kB
6
Indexable
import java.util.PriorityQueue;
public class Solution {
public int eatenApples(int[] apples, int[] days) {
int n = apples.length;
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
int day = 0, eaten = 0;
while (day < n || !heap.isEmpty()) {
// Add apples grown today
if (day < n && apples[day] > 0) {
heap.offer(new int[]{day + days[day], apples[day]});
}
// Remove expired apples
while (!heap.isEmpty() && heap.peek()[0] <= day) {
heap.poll();
}
// Eat an apple
if (!heap.isEmpty()) {
int[] current = heap.poll();
current[1]--; // Eat one apple
eaten++;
// If there are more apples remaining, add them back
if (current[1] > 0) {
heap.offer(current);
}
}
day++;
}
return eaten;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
int[] apples1 = {1, 2, 3, 5, 2};
int[] days1 = {3, 2, 1, 4, 2};
System.out.println(solution.eatenApples(apples1, days1)); // Output: 7
// Example 2
int[] apples2 = {3, 0, 0, 0, 0, 2};
int[] days2 = {3, 0, 0, 0, 0, 2};
System.out.println(solution.eatenApples(apples2, days2)); // Output: 5
}
}
Editor is loading...
Leave a Comment