Partition Array Such That Maximum Difference Is K - Problem

You are given an integer array nums and an integer k. Your task is to partition the array into the minimum number of subsequences such that:

  • Each element appears in exactly one subsequence
  • The difference between the maximum and minimum values in each subsequence is at most k

A subsequence maintains the relative order of elements from the original array (you can skip elements but cannot rearrange them).

Example: If nums = [3,6,1,2,5] and k = 2, you could create subsequences [3,1,2] (max-min = 3-1 = 2 ≤ k) and [6,5] (max-min = 6-5 = 1 ≤ k), giving us 2 subsequences total.

Return the minimum number of subsequences needed to satisfy these conditions.

Input & Output

example_1.py — Basic case
$ Input: nums = [3,6,1,2,5], k = 2
› Output: 2
šŸ’” Note: We can partition into [3,1,2] (max-min = 3-1 = 2 ≤ k) and [6,5] (max-min = 6-5 = 1 ≤ k). Total: 2 subsequences.
example_2.py — All elements fit in one
$ Input: nums = [1,2,3], k = 2
› Output: 1
šŸ’” Note: All elements can fit in one subsequence [1,2,3] since max-min = 3-1 = 2 ≤ k.
example_3.py — Each element needs own subsequence
$ Input: nums = [1,10,20], k = 5
› Output: 3
šŸ’” Note: Each element needs its own subsequence: [1], [10], [20] since any pair would exceed k=5.

Visualization

Tap to expand
Orchestra Section Assignment (k=2)Section 1: Skill Gap ≤ 2312Skills: 1,2,3 → Gap = 3-1 = 2 āœ“Section 2: Skill Gap ≤ 265Skills: 5,6 → Gap = 6-5 = 1 āœ“Processing Order (maintain original sequence):31st62nd13rd24th55thResult: 2 sections needed
Understanding the Visualization
1
First musician (skill 3)
Create first section with skill range [3,3]
2
Second musician (skill 6)
Gap would be 6-3=3 > k=2, so create new section [6,6]
3
Third musician (skill 1)
Can join first section, range becomes [1,3] with gap 2≤k
4
Continue process
Each musician joins the earliest section they can fit in, or starts a new section
Key Takeaway
šŸŽÆ Key Insight: The greedy approach works because we must maintain order - once we decide whether to add an element to an existing subsequence or start a new one, that decision doesn't affect future optimal choices.

Time & Space Complexity

Time Complexity
ā±ļø
O(n²)

For each element, we might check all existing subsequences in worst case

n
2n
⚠ Quadratic Growth
Space Complexity
O(n)

Space to store information about active subsequences

n
2n
⚔ Linearithmic Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ k ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • Elements must maintain their relative order from the original array
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.7K Views
Medium Frequency
~12 min Avg. Time
842 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