LeetCode in Kotlin

1705. Maximum Number of Eaten Apples

Medium

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.

Example 1:

Input: apples = [1,2,3,5,2], days = [3,2,1,4,2]

Output: 7

Explanation: You can eat 7 apples:

Example 2:

Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]

Output: 5

Explanation: You can eat 5 apples:

Constraints:

Solution

import java.util.PriorityQueue

class Solution {
    fun eatenApples(apples: IntArray, days: IntArray): Int {
        val minHeap = PriorityQueue { a: IntArray, b: IntArray -> a[0] - b[0] }
        var eatenApples = 0
        var i = 0
        while (i < apples.size || minHeap.isNotEmpty()) {
            if (i < apples.size) {
                minHeap.offer(intArrayOf(i + days[i], apples[i]))
            }
            while (minHeap.isNotEmpty() && (minHeap.peek()[0] <= i || minHeap.peek()[1] <= 0)) {
                minHeap.poll()
            }
            if (minHeap.isNotEmpty()) {
                eatenApples++
                minHeap.peek()[1]--
            }
            i++
        }
        return eatenApples
    }
}