2033. Minimum Operations to Make a Uni-Value Grid #1481
-
Topics: You are given a 2D integer A uni-value grid is a grid where all the elements of it are equal. Return the minimum number of operations to make the grid uni-value. If it is not possible, return Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of operations required to make all elements in a grid equal by either adding or subtracting a given value Key Points
Approach
Plan
Let's implement this solution in PHP: 2033. Minimum Operations to Make a Uni-Value Grid <?php
/**
* @param Integer[][] $grid
* @param Integer $x
* @return Integer
*/
function minOperations($grid, $x) {
$arr = array();
// Efficiently flatten the grid using element-by-element pushing
foreach ($grid as $row) {
foreach ($row as $num) {
$arr[] = $num;
}
}
if (empty($arr)) {
return 0;
}
// Check if all elements can reach the same value
$base = $arr[0];
foreach ($arr as $num) {
if (($num - $base) % $x !== 0) {
return -1;
}
}
// Find median using optimized sorting
sort($arr);
$median = $arr[(int)(count($arr) / 2)];
// Calculate total operations
$total = 0;
foreach ($arr as $num) {
$total += abs($num - $median) / $x;
}
return $total;
}
// Example test cases
$grid1 = [[15, 96], [36, 2]];
$x1 = 2;
echo minOperations($grid1, $x1) . "\n"; // Output: 4
$grid2 = [[1, 5], [2, 3]];
$x2 = 1;
echo minOperations($grid2, $x2) . "\n"; // Output: 5
$grid3 = [[1, 2], [3, 4]];
$x3 = 2;
echo minOperations($grid3, $x3) . "\n"; // Output: -1
?> Explanation:
Example Walkthrough
Time Complexity
Output for Example This approach efficiently handles the problem constraints and ensures optimal performance by leveraging sorting and median properties. |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of operations required to make all elements in a grid equal by either adding or subtracting a given value
x
each time. If it's not possible to make all elements equal, we should return-1
.Key Points
x
relative to a base element.Approach