All problems
0897MediumArrayGreedySorting

Fewest Crates for the Rods

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2294Partition Array Such That Maximum Difference Is K

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A pile of rods has lengths nums. Rods are packed into crates, and every rod goes into exactly one crate.

A crate is sound when the longest and shortest rod inside it differ by at most k. A crate may hold rods from anywhere in the pile, not just neighbouring ones.

Return the fewest sound crates that hold the whole pile.

Examples

Example 1

Input
nums = [27, 3, 14, 8, 21, 5], k = 6
Output
3

Sorted, the lengths run 3, 5, 8, 14, 21, 27. The first crate takes 3, 5 and 8, since 8 is six above 3. The next takes 14 alone, because 21 is seven above it, and the last takes 21 and 27.

Example 2

Input
nums = [10, 20, 30, 40], k = 10
Output
2

A gap of exactly ten is allowed, so 10 and 20 share a crate and 30 and 40 share another.

Example 3

Input
nums = [1, 2, 3, 4, 5], k = 0
Output
5

With no slack at all, every distinct length needs its own crate.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^5
  • 0 <= k <= 10^5

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def partition_array(nums: list[int], k: int) -> int:
Java
public int partitionArray(int[] nums, int k)
September 7
Apply