LeetCode in Kotlin

3952. Maximum Total Value of Covered Indices

Medium

You are given an integer array nums of length n and a binary string s of length n, where s[i] == '1' means index i initially contains a token and s[i] == '0' means it does not.

You may perform the following operation any number of times:

An index is considered covered if it contains a token after all moves.

Return an integer denoting the maximum total value of nums at the covered indices after optimally performing the operations.

Example 1:

Input: nums = [9,2,6,1], s = “0101”

Output: 15

Explanation:

Example 2:

Input: nums = [5,1,4], s = “001”

Output: 4

Explanation:

Example 3:

Input: nums = [9,3,5], s = “011”

Output: 14

Explanation:

Constraints:

Solution

import kotlin.math.min

class Solution {
    fun maxTotal(nums: IntArray, s: String): Long {
        val n = nums.size
        var mn = 100000
        var res: Long = 0
        for (i in n - 1 downTo 0) {
            res += nums[i].toLong()
            mn = min(mn, nums[i])
            if (s[i] == '0') {
                res -= mn.toLong()
                mn = 100000
            }
        }
        return res
    }
}