Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 6, 2026 20:20
Show Gist options
  • Select an option

  • Save tatsuyax25/b20fcd102b28a9bee9c419d2a14838bf to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/b20fcd102b28a9bee9c419d2a14838bf to your computer and use it in GitHub Desktop.
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. Retur
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minRemoval = function(nums, k) {
// Step 1: Sort the array so window are contiguous and ordered
nums.sort((a, b) => a - b);
let n = nums.length;
let i = 0; // left pointer (minimum in window)
let maxWindow = 1; // at least one element is always balanced
// Step 2: Slide the right pointer j across the array
for (let j = 0; j < n; j++) {
// Step 3: If window becomes invalid, move i forward
// Condition for invalid window:
// nums[j] > k * nums[i]
while (nums[j] > k * nums[i]) {
i++; // shrink from the left until valid
}
// Step 4: Update the largest valid window size
maxWindow = Math.max(maxWindow, j - i + 1);
}
// Step 5: Minimum removals = total - largest balanced window
return n - maxWindow;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment