|
| 1 | +# 2966. Divide Array Into Arrays With Max Difference |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Greedy, Sorting. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +You are given an integer array `nums` of size `n` and a positive integer `k`. |
| 10 | + |
| 11 | +Divide the array into one or more arrays of size `3` satisfying the following conditions: |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +- **Each** element of `nums` should be in **exactly** one array. |
| 16 | + |
| 17 | +- The difference between **any** two elements in one array is less than or equal to `k`. |
| 18 | + |
| 19 | + |
| 20 | +Return **a ****2D**** array containing all the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return **any** of them.** |
| 21 | + |
| 22 | + |
| 23 | +Example 1: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: nums = [1,3,4,8,7,9,3,5,1], k = 2 |
| 27 | +Output: [[1,1,3],[3,4,5],[7,8,9]] |
| 28 | +Explanation: We can divide the array into the following arrays: [1,1,3], [3,4,5] and [7,8,9]. |
| 29 | +The difference between any two elements in each array is less than or equal to 2. |
| 30 | +Note that the order of elements is not important. |
| 31 | +``` |
| 32 | + |
| 33 | +Example 2: |
| 34 | + |
| 35 | +``` |
| 36 | +Input: nums = [1,3,3,2,7,3], k = 3 |
| 37 | +Output: [] |
| 38 | +Explanation: It is not possible to divide the array satisfying all the conditions. |
| 39 | +``` |
| 40 | + |
| 41 | + |
| 42 | +**Constraints:** |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +- `n == nums.length` |
| 47 | + |
| 48 | +- `1 <= n <= 105` |
| 49 | + |
| 50 | +- `n` is a multiple of `3`. |
| 51 | + |
| 52 | +- `1 <= nums[i] <= 105` |
| 53 | + |
| 54 | +- `1 <= k <= 105` |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | +## Solution |
| 59 | + |
| 60 | +```javascript |
| 61 | +/** |
| 62 | + * @param {number[]} nums |
| 63 | + * @param {number} k |
| 64 | + * @return {number[][]} |
| 65 | + */ |
| 66 | +var divideArray = function(nums, k) { |
| 67 | + nums.sort((a, b) => a - b); |
| 68 | + var res = []; |
| 69 | + for (var i = 0; i < nums.length; i += 3) { |
| 70 | + if (nums[i + 2] - nums[i] <= k) { |
| 71 | + res.push([nums[i], nums[i + 1], nums[i + 2]]); |
| 72 | + } else { |
| 73 | + return []; |
| 74 | + } |
| 75 | + } |
| 76 | + return res; |
| 77 | +}; |
| 78 | +``` |
| 79 | + |
| 80 | +**Explain:** |
| 81 | + |
| 82 | +nope. |
| 83 | + |
| 84 | +**Complexity:** |
| 85 | + |
| 86 | +* Time complexity : O(n * log(n)). |
| 87 | +* Space complexity : O(n). |
0 commit comments