LeetCode in Kotlin

3864. Minimum Cost to Partition a Binary String

Hard

You are given a binary string s and two integers encCost and flatCost.

For each index i, s[i] = '1' indicates that the ith element is sensitive, and s[i] = '0' indicates that it is not.

The string must be partitioned into segments. Initially, the entire string forms a single segment.

For a segment of length L containing X sensitive elements:

If a segment has even length, you may split it into two contiguous segments of equal length and the cost of this split is the sum of costs of the resulting segments.

Return an integer denoting the minimum possible total cost over all valid partitions.

Example 1:

Input: s = “1010”, encCost = 2, flatCost = 1

Output: 6

Explanation:

Example 2:

Input: s = “1010”, encCost = 3, flatCost = 10

Output: 12

Explanation:

Example 3:

Input: s = “00”, encCost = 1, flatCost = 2

Output: 2

Explanation:

The string s = "00" has length 2 and contains no sensitive elements, so storing it as a single segment costs flatCost = 2, which is the minimum possible total cost.

Constraints:

Solution

import kotlin.math.min

class Solution {
    private var encCost = 0
    private var flatCost = 0
    private lateinit var pre: IntArray

    fun minCost(s: String, encCost: Int, flatCost: Int): Long {
        pre = IntArray(s.length + 1)
        for (i in 1..<pre.size) {
            pre[i] = pre[i - 1] + (s[i - 1].code - '0'.code)
        }
        this.encCost = encCost
        this.flatCost = flatCost
        return helper(0, s.length)
    }

    private fun helper(l: Int, r: Int): Long {
        val gap = r - l
        val x = pre[r] - pre[l]
        if (x == 0) {
            return flatCost.toLong()
        }
        var cost = gap.toLong() * x * encCost
        if (gap % 2 == 0) {
            val mid = l + (r - l) / 2
            cost = min(cost, helper(l, mid) + helper(mid, r))
        }
        return cost
    }
}