Input: grid =[[2,4],[6,8]], x =2Output: 4Explanation: We can make every element equal to 4 by doing the following:- Add x to 2 once.- Subtract x from 6 once.- Subtract x from 8 twice.A total of 4 operations were used.
A grid is uni-value if all the elements equal the same value. For this to be possible, all the grid elements must have the same remainder when divided by x (i.e., grid[i][j] % x must be consistent). If this condition fails, return -1, as transforming the grid is impossible.
Flatten the grid into a 1D list.
Check divisibility, as explained above.
Use the median of the flattened list to minimise operations (because the median minimises the sum of absolute differences in a sorted list).
Calculate the total cost by summing the number of operations needed to adjust all elements to the median value.
classSolution {
publicintminOperations(int[][] grid, int x) {
// Flatten the grid into 1D array List<Integer> flatGrid =new ArrayList<>();
for (int[] row : grid) {
for (int num : row) {
flatGrid.add(num);
}
}
// Check if all numbers are divisible consistently by xint remainder = flatGrid.get(0) % x;
for (int num : flatGrid) {
if (num % x != remainder) {
return-1;
}
}
// Sort the grid and find the median Collections.sort(flatGrid);
int median = flatGrid.get(flatGrid.size() / 2);
// Calculate the total operationsint ans = 0;
for (int num : flatGrid) {
ans += Math.abs(num - median) / x;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defminOperations(self, grid: List[List[int]], x: int) -> int:
# Flatten the grid into 1D list flat_grid = [num for row in grid for num in row]
# Check if all numbers are divisible consistently by x remainder = flat_grid[0] % x
if any(num % x != remainder for num in flat_grid):
return-1# Sort the grid and find the median flat_grid.sort()
median = flat_grid[len(flat_grid) //2]
# Calculate the total operations ans = sum(abs(num - median) // x for num in flat_grid)
return ans