# 2033. Minimum Operations to Make a Uni-Value Grid

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FEEg3vgVA40a2Sv5xa34L%2Fimage.png?alt=media\&token=2556e2d3-9511-4d2f-8103-32f82174b024)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2Fs9a6MBfzgTM4SiLnb9r6%2Fimage.png?alt=media\&token=9f79131a-bd00-4b56-907c-cd6776806b8d)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2Fn1hf8cm73WJkFwr27BdV%2Fimage.png?alt=media\&token=abbc3ff1-24f5-416c-bf4d-dd33293b750a)

time: O(mnlogmn)

space: O(mn)

```java
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;
    }
}
```

