LeetCode in Kotlin

2105. Watering Plants II

Medium

Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.

Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way:

Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice’s and Bob’s watering cans respectively, return the number of times they have to refill to water all the plants.

Example 1:

Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5

Output: 1

Explanation:

So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.

Example 2:

Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4

Output: 2

Explanation:

So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.

Example 3:

Input: plants = [5], capacityA = 10, capacityB = 8

Output: 0

Explanation:

So, the total number of times they have to refill is 0.

Constraints:

Solution

@Suppress("NAME_SHADOWING")
class Solution {
    fun minimumRefill(plants: IntArray, capacityA: Int, capacityB: Int): Int {
        var capacityA = capacityA
        var capacityB = capacityB
        val n = plants.size
        var i = 0
        var j = n - 1
        var aRefill = 0
        var bRefill = 0
        val initialCapacityA = capacityA
        val initialCapacityB = capacityB
        while (i <= j) {
            if (i == j) {
                if (!(capacityA >= plants[i] || capacityB >= plants[i])) {
                    aRefill++
                }
                i++
                continue
            }
            capacityA = if (capacityA >= plants[i]) {
                capacityA - plants[i]
            } else {
                aRefill++
                initialCapacityA - plants[i]
            }
            capacityB = if (capacityB >= plants[j]) {
                capacityB - plants[j]
            } else {
                bRefill++
                initialCapacityB - plants[j]
            }
            i++
            j--
        }
        return aRefill + bRefill
    }
}