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
Partition Array - Maximum Difference K INPUT nums = [4, 6, 1, 2] 4 6 1 2 [0] [1] [2] [3] k = 2 Max difference in each subsequence must be at most k Goal: Find minimum number of valid subsequences ALGORITHM STEPS 1 Sort the Array [1, 2, 4, 6] 1 2 4 6 2 Start First Group Start with min=1 3 Extend Greedily Add elements while max - min <= k 4 New Group When Difference exceeds k count++ Group1: [1,2] (2-1=1 <= 2) Group2: [4,6] (6-4=2 <= 2) 4-1=3 > k, so new group! FINAL RESULT Minimum Subsequences: 2 Subsequence 1: 1 2 diff=1 Subsequence 2: 4 6 diff=2 Verification: OK All elements covered All diffs <= k=2 Key Insight: Sorting enables greedy grouping: consecutive elements in sorted order have minimum differences. Start each group with smallest available element, extend until max - min > k, then start new group. Time: O(n log n) for sorting | Space: O(1) extra space TutorialsPoint - Partition Array Such That Maximum Difference Is K | Greedy Approach After Sorting
Asked in
Google 25 Microsoft 18 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen