LeetCode 1705: Maximum Number of Eaten Apples Solution

Master LeetCode problem 1705 (Maximum Number of Eaten Apples), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1705. Maximum Number of Eaten Apples

Problem Explanation

Explanation

To maximize the number of apples eaten, we need to prioritize eating apples that will rot soonest. We can simulate the process day by day, keeping track of the available apples each day and eating the ripest apple possible. We can use a priority queue to store the apples based on their rotting day, ensuring that we always eat the apple that will rot soonest.

  1. Initialize a priority queue to store the apples, sorted by their rotting day.
  2. Iterate through the days:
    • Add new apples to the priority queue.
    • Pop and eat the ripest apple each day, updating the total count of eaten apples and decrementing the days until rotting for remaining apples.
    • Continue until reaching the end of the given days.
  3. Return the total count of eaten apples.

Time Complexity: O(n*log(n)) where n is the number of days Space Complexity: O(n) for the priority queue storing apples

Solution Code

import java.util.PriorityQueue;

class Solution {
    public int eatenApples(int[] apples, int[] days) {
        int n = apples.length;
        int eaten = 0;
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[0] - b[0]);

        for (int i = 0; i < n || !queue.isEmpty(); i++) {
            if (i < n && apples[i] > 0) {
                queue.offer(new int[]{i + days[i], apples[i]});
            }

            while (!queue.isEmpty() && (queue.peek()[0] <= i || queue.peek()[1] == 0)) {
                queue.poll();
            }

            if (!queue.isEmpty()) {
                int[] apple = queue.poll();
                eaten++;
                apple[1]--;
                if (apple[1] > 0) {
                    queue.offer(apple);
                }
            }
        }

        return eaten;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1705 (Maximum Number of Eaten Apples)?

This page provides optimized solutions for LeetCode problem 1705 (Maximum Number of Eaten Apples) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1705 (Maximum Number of Eaten Apples)?

The time complexity for LeetCode 1705 (Maximum Number of Eaten Apples) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1705 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1705 in Java, C++, or Python.

Back to LeetCode Solutions