2966. Divide Array Into Arrays With Max Difference #1822
-
Topics: You are given an integer array Divide the array
Return a 2D array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to divide an integer array into multiple arrays of size 3 such that the difference between any two elements in each sub-array is less than or equal to a given integer Approach
This approach leverages the fact that sorting the array allows us to form triplets with the smallest possible differences between elements. By checking consecutive triplets, we ensure that any valid grouping will satisfy the condition, and if any triplet fails, no valid grouping exists. Let's implement this solution in PHP: 2966. Divide Array Into Arrays With Max Difference <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer[][]
*/
function divideArray($nums, $k) {
sort($nums);
$n = count($nums);
$result = array();
for ($i = 0; $i < $n; $i += 3) {
if ($i + 2 >= $n) {
break;
}
if ($nums[$i + 2] - $nums[$i] > $k) {
return array();
}
$result[] = array($nums[$i], $nums[$i + 1], $nums[$i + 2]);
}
return $result;
}
// Test cases
// Example 1
$nums = array(1,3,4,8,7,9,3,5,1);
$k = 2;
print_r(divideArray($nums, $k));
// Example 2
$nums = array(2,4,2,2,5,2);
$k = 2;
print_r(divideArray($nums, $k));
// Example 3
$nums = array(4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11);
$k = 14;
print_r(divideArray($nums, $k));
?> Explanation:
This approach efficiently checks for valid groupings by leveraging sorting and a linear pass through the array, making it optimal with a time complexity dominated by the sorting step, O(n log n). The space complexity is O(n) to store the result triplets. |
Beta Was this translation helpful? Give feedback.
We need to divide an integer array into multiple arrays of size 3 such that the difference between any two elements in each sub-array is less than or equal to a given integer
k
. If it's impossible to satisfy the conditions, we return an empty array.Approach