#2294
Partition Array Such That Maximum Difference Is K
MediumArrayGreedySortingGreedySortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the array first, we can efficiently group elements together. The maximum difference condition can be checked in a linear pass, allowing us to minimize the number of subsequences needed.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array nums.
- 2Step 2: Initialize a counter for subsequences and set the first element as the start of the first subsequence.
- 3Step 3: Iterate through the sorted array, and for each element, check if it can fit into the current subsequence (i.e., if the difference with the start is <= k).
- 4Step 4: If it can't fit, increment the subsequence counter and start a new subsequence with the current element.
- 5Step 5: Return the total count of subsequences.
solution.py10 lines
1# Full working Python code
2def min_partitions(nums, k):
3 nums.sort()
4 count = 1
5 start = nums[0]
6 for num in nums:
7 if num - start > k:
8 count += 1
9 start = num
10 return countℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the linear pass through the array is O(n). This is efficient compared to the brute force approach.
- 1The maximum and minimum values in a subsequence are critical for determining if it can be formed.
- 2Sorting the array allows us to efficiently group elements that can fit within the difference constraint.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.