LeetCode in Kotlin

2511. Maximum Enemy Forts That Can Be Captured

Easy

You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -1, 0, or 1 where:

Now you have decided to move your army from one of your forts at position i to an empty position j such that:

While moving the army, all the enemy forts that come in the way are captured.

Return the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.

Example 1:

Input: forts = [1,0,0,-1,0,0,0,0,1]

Output: 4

Explanation:

Since 4 is the maximum number of enemy forts that can be captured, we return 4.

Example 2:

Input: forts = [0,0,1,-1]

Output: 0

Explanation: Since no enemy fort can be captured, 0 is returned.

Constraints:

Solution

class Solution {
    fun captureForts(forts: IntArray): Int {
        var maxCapture = 0
        val n = forts.size
        var i = 0
        while (i < n) {
            if (forts[i] == 1) {
                var currMax = 0
                i++
                while (i < n && forts[i] == 0) {
                    currMax++
                    i++
                }
                if (i < n && forts[i] == -1) {
                    maxCapture = Math.max(maxCapture, currMax)
                }
                i--
            } else if (forts[i] == -1) {
                var currMax = 0
                i++
                while (i < n && forts[i] == 0) {
                    currMax++
                    i++
                }
                if (i < n && forts[i] == 1) {
                    maxCapture = Math.max(maxCapture, currMax)
                }
                i--
            }
            i++
        }
        return maxCapture
    }
}