↓Skip to main content
  1. LeetCode/

LeetCode 2294: Partition Array Such That Maximum Difference Is K

·1 min· ·
LeetCode Medium Greedy Sorting Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-09-03

  • Submissions: Accepted (first try)

Approach
#

A group only cares about max minus min, not order, so sort first. Start a group at the smallest number and add everything <= start + k; the first number beyond that starts a new group.

Why extending as far as possible is right: the smallest number is in some group, and that group can reach at most start + k; taking more only leaves fewer numbers for later. This is Greedy Template 1.

My Solution
#

class Solution:
    def partitionArray(self, nums: List[int], k: int) -> int:
        nums.sort()
        groups = 1
        start = nums[0]
        for x in nums[1:]:
            if x - start > k:
                groups += 1
                start = x
        return groups

Complexity
#

Time O(n log n), space O(1) besides sorting.

Mistakes to Avoid
#

  • Compare with the group’s minimum, not with the previous number.

Interview Explanation
#

Subsequences ignore order, so I sort. I open a group at the smallest number and include everything within k of it, starting a new group when that fails. The group holding the smallest number can only reach that far anyway, so extending it fully is never worse. Time O(n log n).

Related

LeetCode 2410: Maximum Matching of Players With Trainers
·2 mins
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 2410 note: sort both sides, then same-direction pointers match the weakest player with the smallest trainer that is good enough
LeetCode 3627: Maximum Median Sum of Subsequences of Size 3
·2 mins
LeetCode Medium Math Greedy Sorting Game-Theory Array
LeetCode 3627 note: after sorting, each group takes the two largest and the smallest, with the second largest as the median; the answer takes every other value from the end, n / 3 of them
LeetCode 3075: Maximize Happiness of Selected Children
·1 min
LeetCode Medium Array Greedy Sorting
LeetCode 3075 note: choose k children from the happiest, where the i-th choice loses i, floored at 0
LeetCode 324: Wiggle Sort II
·2 mins
LeetCode Medium Array Divide-and-Conquer Greedy Sorting
LeetCode 324 note: sort, split into a small half and a large half, reverse each, and interleave with small values at even indices and large ones at odd indices
LeetCode 435: Non-overlapping Intervals
·2 mins
LeetCode Medium Array Dynamic-Programming Greedy Sorting
LeetCode 435 note: minimum removals = total minus the maximum kept; sort by right end and greedily keep the one ending earliest
LeetCode 853: Car Fleet
·2 mins
LeetCode Daily Medium Array Stack Greedy Simulation Sorting
Solving the Car Fleet problem using stack-based approach