Partition Array Such That Maximum Difference Is K - Problem
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 difference between the maximum and minimum values in each subsequence is at most k.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,6,1,2], k = 2
›
Output:
2
💡 Note:
After sorting [1,2,4,6], we can partition into {1,2} (diff=1≤2) and {4,6} (diff=2≤2). Need 2 subsequences.
Example 2 — Single Subsequence
$
Input:
nums = [1,2,3], k = 2
›
Output:
1
💡 Note:
All elements fit in one subsequence since max-min = 3-1 = 2 ≤ k=2.
Example 3 — All Separate
$
Input:
nums = [1,4,7,10], k = 2
›
Output:
4
💡 Note:
Each element needs its own subsequence since consecutive differences are all > 2.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ k ≤ 105
- 0 ≤ nums[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [4,6,1,2] and k=2
2
Process
Sort and group greedily
3
Output
Minimum 2 subsequences needed
Key Takeaway
🎯 Key Insight: Sorting enables greedy partitioning since we only need to track minimum of current group
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code