Skip to content

2966. Divide Array Into Arrays With Max Difference 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<vector<int>> divideArray(vector<int>& nums, int k) {
    vector<vector<int>> ans;

    ranges::sort(nums);

    for (int i = 2; i < nums.size(); i += 3) {
      if (nums[i] - nums[i - 2] > k)
        return {};
      ans.push_back({nums[i - 2], nums[i - 1], nums[i]});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int[][] divideArray(int[] nums, int k) {
    int[][] ans = new int[nums.length / 3][3];

    Arrays.sort(nums);

    for (int i = 2; i < nums.length; i += 3) {
      if (nums[i] - nums[i - 2] > k)
        return new int[0][];
      ans[i / 3] = new int[] {nums[i - 2], nums[i - 1], nums[i]};
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def divideArray(self, nums: list[int], k: int) -> list[list[int]]:
    ans = []

    nums.sort()

    for i in range(2, len(nums), 3):
      if nums[i] - nums[i - 2] > k:
        return []
      ans.append([nums[i - 2], nums[i - 1], nums[i]])

    return ans