#2966. Divide Array Into Arrays With Max Difference

ยท

1 min read

https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/description/?source=submission-ac


const divideArray = function (nums, k) {
    nums.sort((a, b) => a - b);

    let result = [];

    for (let i = 2; i < nums.length; i += 3) {
        if (nums[i] - nums[i - 2] > k) return [];

        result.push([nums[i - 2], nums[i - 1], nums[i]]);
    }

    return result;
};

First, we sort the given array.

We loop in threes and find the difference between the first and the last number in each set.

If it is greater than k, we return an empty array.

If not, we put the set in an array and push it to result array.

Finally, the result is returned.

ย