Partition Array Such That Maximum Difference Is K — LeetCode 2294 Python Solution
- Problem
- #2294
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [3,6,1,2,5], k = 2
- Output
- 2
- Explanation
- We can partition nums into the two subsequences [3,1,2] and [6,5].
Python solution
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
ans, a = 1, nums[0]
for b in nums:
if b - a > k:
a = b
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2294. Partition Array Such That Maximum Difference Is K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2294. Partition Array Such That Maximum Difference Is K?
- LeetCode 2294. Partition Array Such That Maximum Difference Is K is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2294. Partition Array Such That Maximum Difference Is K?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2294. Partition Array Such That Maximum Difference Is K?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2294. Partition Array Such That Maximum Difference Is K cover?
- LeetCode 2294. Partition Array Such That Maximum Difference Is K is tagged Greedy, Array and Sorting on LeetCode.