Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active February 13, 2025 22:11
Show Gist options
  • Save tatsuyax25/cb31a01fb76c049738814e1ba2703ee5 to your computer and use it in GitHub Desktop.
Save tatsuyax25/cb31a01fb76c049738814e1ba2703ee5 to your computer and use it in GitHub Desktop.
You are given a 0-indexed integer array nums, and an integer k. You are allowed to perform some operations on nums, where in a single operation, you can: Select the two smallest integers x and y from nums. Remove x and y from nums. Insert (min(x, y
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var minOperations = function(nums, k) {
let queue = [], ans = 0, i = 0;
// Sort nums in descending order
nums.sort((a, b) => b - a);
// Process nums and queue until both are empty
while(nums.length + queue.length > 0){
let x = 0, y = 0;
// Check if the smallest elements in nums and queue are both >= k
if((!nums[nums.length -1 ] || nums[nums.length - 1] >= k) && (!queue[i] || queue[i] >= k)){
return ans;
}
// Assign the smaller value between nums and queue to x
if(nums[nums.length-1] && nums[nums.length-1] < (queue[i] || Infinity)){
x = nums.pop();
} else {
x = queue[i];
i++;
}
// Assign the next smaller value between nums and queue to y
if(nums[nums.length-1] && nums[nums.length-1] < (queue[i] || Infinity)){
y = nums.pop();
} else {
y = queue[i];
i++;
}
// Calculate the new value to push to the queue
let op = x * 2 + y;
// Add the new value to the queue
queue.push(op);
// Increment the number of operations
ans++;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment