class Solution {
public int minOperations(int[][] grid, int x) {
int m = grid.length;
int n = grid[0].length;
int mod = grid[0][0]%x;
int data[] = new int[m*n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
data[i*n + j] = grid[i][j];
if (grid[i][j] % x != mod) {
return -1;
}
}
}
Arrays.sort(data);
int median = data[m*n/2];
int operation = 0;
for (int i = 0; i < m*n; i++) {
operation += Math.abs(data[i]-median)/x;
}
// 1 2 3 4
if (m*n % 2 == 0) {
int median2 = data[(m*n/2)-1]; // 偶數的話, 取前一個
int operation2 = 0;
for (int i = 0; i < m*n; i++) {
operation2 += Math.abs(data[i]-median2)/x;
}
operation = Math.min(operation, operation2);
}
return operation;
}
}