The Partition Array Such That Maximum Difference Is K problem asks you to partition the array into the minimum number of contiguous groups such that within each group, max - min ≤ k. Return the minimum number of groups. This coding problem uses a greedy approach after sorting. The array, sorting, and greedy interview pattern is demonstrated.
Amazon and Google ask this to test greedy reasoning on sorted arrays. The key insight: sort the array, then greedily extend each group as far as possible while current - group_start ≤ k. This gives the minimum number of groups.
Sort + greedy sweep. Sort the array. Initialize group_start = arr[0], count = 1. Scan from left: if arr[i] - group_start > k, start a new group (group_start = arr[i], count++). Return count.
arr=[3,6,1,2,5], k=2. Sort: [1,2,3,5,6].
arr[i] - arr[i-1] > k instead of arr[i] - group_start > k."Minimum groups with max-min ≤ k" is a classic greedy interval partition. After sorting, the problem becomes one-dimensional: greedily extend each interval until it exceeds width k. This identical pattern appears in "minimum number of jumps," "interval scheduling," and "merge overlapping intervals." Sorting + greedy sweep is the universal approach for range-constrained grouping.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Destroying Asteroids | Medium | Solve | |
| Minimum Cost to Make Arrays Identical | Medium | Solve | |
| Find Minimum Time to Finish All Jobs II | Medium | Solve | |
| Maximize Happiness of Selected Children | Medium | Solve | |
| Maximum Bags With Full Capacity of Rocks | Medium | Solve |