LeetCode in Kotlin

1717. Maximum Score From Removing Substrings

Medium

You are given a string s and two integers x and y. You can perform two types of operations any number of times.

Return the maximum points you can gain after applying the above operations on s.

Example 1:

Input: s = “cdbcbbaaabab”, x = 4, y = 5

Output: 19

Explanation:

Example 2:

Input: s = “aabbaaxybbaabb”, x = 5, y = 4

Output: 20

Constraints:

Solution

class Solution {
    fun maximumGain(s: String, x: Int, y: Int): Int {
        val v = s.toCharArray()
        return if (x > y) {
            helper(v, 'a', 'b', x) + helper(v, 'b', 'a', y)
        } else {
            helper(v, 'b', 'a', y) + helper(v, 'a', 'b', x)
        }
    }

    private fun helper(v: CharArray, c1: Char, c2: Char, score: Int): Int {
        var left = -1
        var right = 0
        var res = 0
        while (right < v.size) {
            if (v[right] != c2) {
                left = right
            } else {
                while (left >= 0) {
                    val cl = v[left]
                    if (cl == '#') {
                        left--
                    } else if (cl == c1) {
                        res += score
                        v[left] = '#'
                        v[right] = '#'
                        left--
                        break
                    } else {
                        break
                    }
                }
            }
            right++
        }
        return res
    }
}