LeetCode in Kotlin

2366. Minimum Replacements to Sort the Array

Hard

You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.

Return the minimum number of operations to make an array that is sorted in non-decreasing order.

Example 1:

Input: nums = [3,9,3]

Output: 2

Explanation: Here are the steps to sort the array in non-decreasing order:

There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.

Example 2:

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

Output: 0

Explanation: The array is already in non-decreasing order. Therefore, we return 0.

Constraints:

Solution

class Solution {
    fun minimumReplacement(nums: IntArray): Long {
        var limit = nums[nums.size - 1]
        var ans: Long = 0
        for (i in nums.size - 2 downTo 0) {
            var replacements = nums[i] / limit - 1
            if (nums[i] % limit != 0) {
                replacements++
            }
            ans += replacements.toLong()
            limit = nums[i] / (replacements + 1)
        }
        return ans
    }
}