Divide Array Into Arrays With Max Difference

Medium Topics Company Tags

Partition all the elements of nums into groups of exactly three. Within each group, the largest and smallest values must differ by at most k. Every occurrence of a value must be used exactly once.

Return the groups in any order, with their elements in any order. If more than one partition works, any valid partition is accepted. Return an empty array if no partition is possible. The length of nums is divisible by three.

Example 1:

Input: nums = [6,2,3,7,1,8]
k = 2

Output: [[6,7,8],[2,3,1]]

Explanation: The groups [6,7,8] and [2,3,1] use every element once. Each group has largest-minus-smallest equal to 2.

Example 2:

Input: nums = [1,1,1,2,2,9]
k = 2

Output: []

Explanation: The value 9 must share a group with two values no larger than 2. That group would exceed the allowed difference of 2, so no partition works.

Example 3:

Input: nums = [1,2,3,4,5,6]
k = 5

Output: [[1,2,3],[4,5,6]]

Explanation: One valid answer is [[1,2,3],[4,5,6]]. Another is [[1,3,5],[2,4,6]]. Each group has three elements and a difference of at most 5.

Constraints:

  • 3 <= nums.length <= 100000
  • nums.length is divisible by 3.
  • 1 <= nums[i] <= 100000
  • 1 <= k <= 100000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.