Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 19, 2025 01:19
Show Gist options
  • Save tatsuyax25/add1f2b23ac50357cb5a3bc17eb2165b to your computer and use it in GitHub Desktop.
Save tatsuyax25/add1f2b23ac50357cb5a3bc17eb2165b to your computer and use it in GitHub Desktop.
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. Return the minimum number of subsequences needed such that the diff
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var partitionArray = function(nums, k) {
if (nums.length === 0) return 0;
// Step 1: Sort the array so that we can group close numbers together
nums.sort((a, b) => a - b);
let count = 1; // At least one subsequence to start
let start = nums[0]; // Start of the current subsequence
// Step 2: Iterate through the sorted array
for (let i = 1; i < nums.length; i++) {
// If the current number is too far from the start of the subsequence,
// we start a new group
if (nums[i] - start > k) {
count++;
start = nums[i]; // Reset the start to the new group's first number
}
}
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment