LeetCode in Kotlin

2106. Maximum Fruits Harvested After at Most K Steps

Hard

Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique.

You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.

Return the maximum total number of fruits you can harvest.

Example 1:

Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4

Output: 9

Explanation: The optimal way is to:

You moved 3 steps and harvested 3 + 6 = 9 fruits in total.

Example 2:

Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4

Output: 14

Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to:

You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.

Example 3:

Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2

Output: 0

Explanation: You can move at most k = 2 steps and cannot reach any position with fruits.

Constraints:

Solution

class Solution {
    fun maxTotalFruits(fruits: Array<IntArray>, startPos: Int, k: Int): Int {
        var res = 0
        var sum = 0
        var left = 0
        for (right in fruits.indices) {
            sum += fruits[right][1]
            while (left <= right && !isValidRange(fruits[left][0], fruits[right][0], startPos, k)) {
                sum -= fruits[left++][1]
            }
            res = Math.max(sum, res)
        }
        return res
    }

    private fun isValidRange(leftPos: Int, rightPos: Int, startPos: Int, k: Int): Boolean {
        val result: Boolean
        result = if (rightPos <= startPos) {
            startPos - leftPos <= k
        } else if (leftPos >= startPos) {
            rightPos - startPos <= k
        } else {
            val left = startPos - leftPos
            val right = rightPos - startPos
            if (left <= right) left * 2 + right <= k else right * 2 + left <= k
        }
        return result
    }
}