LeetCode in Kotlin

2155. All Divisions With the Highest Score of a Binary Array

Medium

You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:

The division score of an index i is the sum of the number of 0’s in numsleft and the number of 1’s in numsright.

Return all distinct indices that have the highest possible division score. You may return the answer in any order.

Example 1:

Input: nums = [0,0,1,0]

Output: [2,4]

Explanation: Division at index

Indices 2 and 4 both have the highest possible division score 3.

Note the answer [4,2] would also be accepted.

Example 2:

Input: nums = [0,0,0]

Output: [3]

Explanation: Division at index

Only index 3 has the highest possible division score 3.

Example 3:

Input: nums = [1,1]

Output: [0]

Explanation: Division at index

Only index 0 has the highest possible division score 2.

Constraints:

Solution

class Solution {
    fun maxScoreIndices(nums: IntArray): List<Int> {
        var curone = 0
        var curzero = 0
        var max = 0
        for (i in nums) {
            curone += i
        }
        val list: MutableList<Int> = ArrayList()
        for (i in nums.indices) {
            if (curzero + curone > max) {
                list.clear()
                list.add(i)
                max = curzero + curone
            } else if (curzero + curone == max) {
                list.add(i)
            }
            if (nums[i] == 1) {
                curone--
            } else {
                curzero++
            }
        }
        if (curzero > max) {
            list.clear()
            list.add(nums.size)
        } else if (curzero == max) {
            list.add(nums.size)
        }
        return list
    }
}