Divide Array Into Arrays With Max Difference

Given an array and an integer k, divide the array into groups of three such that the maximum difference in each group is at most k. Sorting the bounded values first makes the grouping check simple.

Input Format

nums = array of integers, k = maximum allowed difference per group

Output Format

3-number groups after sorting if possible

Constraints

  • 3 <= nums.length <= 10^5; nums.length is divisible by 3; 0 <= nums[i], k <= 10^5

Examples

Example 1:

Input:

nums = [1,3,4,8,7,9,3,5,1]
k = 2

Output:

[[1,1,3],[3,4,5],[7,8,9]]

Explanation:

After sorting, each group of 3 has max-min <= 2.

Example 2:

Input:

nums = [1,3,3,2,7,3]
k = 3

Output:

[]

Explanation:

The sorted array can be partitioned into valid size-3 groups.

Loading...
Divide Array Into Arrays With Max Difference