LeetCode in Kotlin

3634. Minimum Removals to Balance Array

Medium

You are given an integer array nums and an integer k.

An array is considered balanced if the value of its maximum element is at most k times the minimum element.

You may remove any number of elements from nums without making it empty.

Return the minimum number of elements to remove so that the remaining array is balanced.

Note: An array of size 1 is considered balanced as its maximum and minimum are equal, and the condition always holds true.

Example 1:

Input: nums = [2,1,5], k = 2

Output: 1

Explanation:

Example 2:

Input: nums = [1,6,2,9], k = 3

Output: 2

Explanation:

Example 3:

Input: nums = [4,6], k = 2

Output: 0

Explanation:

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun minRemoval(nums: IntArray, k: Int): Int {
        // Sort array to maintain order
        nums.sort()
        val n = nums.size
        var maxSize = 0
        var left = 0
        // Use sliding window to find longest valid subarray
        for (right in 0..<n) {
            // While condition is violated, shrink window from left
            while (nums[right] > k.toLong() * nums[left]) {
                left++
            }
            maxSize = max(maxSize, right - left + 1)
        }
        // Return number of elements to remove
        return n - maxSize
    }
}