LeetCode in Kotlin

3891. Minimum Increase to Maximize Special Indices

Medium

You are given an integer array nums of length n.

An index i (0 < i < n - 1) is special if nums[i] > nums[i - 1] and nums[i] > nums[i + 1].

You may perform operations where you choose any index i and increase nums[i] by 1.

Your goal is to:

Return an integer denoting the minimum total number of operations required.

Example 1:

Input: nums = [1,2,2]

Output: 1

Explanation:

Example 2:

Input: nums = [2,1,1,3]

Output: 2

Explanation:

Example 3:

Input: nums = [5,2,1,4,3]

Output: 4

Explanation:

Constraints:

Solution

import kotlin.math.max
import kotlin.math.min

class Solution {
    fun minIncrease(nums: IntArray): Long {
        val n = nums.size
        var min: Long = 0
        if ((n and 1) == 1) {
            var i = 1
            while (i < n) {
                min += max(max(nums[i - 1], nums[i + 1]) + 1 - nums[i], 0).toLong()
                i += 2
            }
        } else {
            val starting = longArrayOf(0, 0)
            var i = 1
            while (i < n - 1) {
                val firstOp = max(max(nums[i - 1], nums[i + 1]) + 1 - nums[i], 0)
                val secondOp = max(max(nums[i], nums[i + 2]) + 1 - nums[i + 1], 0)
                starting[1] = min(starting[0], starting[1]) + secondOp
                starting[0] += firstOp.toLong()
                i += 2
            }
            min = min(starting[0], starting[1])
        }
        return min
    }
}