[LeetCode] Divide Array Into Arrays With Max Difference

2966. Divide Array Into Arrays With Max Difference

You are given an integer array nums of size n and a positive integer k.

Divide the array into one or more arrays of size 3 satisfying the following conditions:

  • Each element of nums should be in exactly one array.
  • The difference between any two elements in one array is less than or equal to k.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<vector<int>> divideArray(vector<int>& A, int k) {
int n = A.size();
if(n % 3) return {};
sort(begin(A), end(A));
vector<vector<int>> res;
for(int i = 0; i < n; i += 3) {
vector<int> now{A[i], A[i+1], A[i+2]};
if(now.back() - now.front() > k) return {};
res.push_back(now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/17/PS/LeetCode/divide-array-into-arrays-with-max-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.