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
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
ā Quadratic Growth
Space Complexity
O(n)
Space to store information about active subsequences
ā” Linearithmic Space
Constraints
- 1 ⤠nums.length ⤠105
- 0 ⤠k ⤠105
- 1 ⤠nums[i] ⤠105
- Elements must maintain their relative order from the original array
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code