> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/math/2033.-minimum-operations-to-make-a-uni-value-grid.md).

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

![](/files/GdkHBcpXyuTgtmlRbbp2)

![](/files/hzwdrJXkUw6iu2nQRXsf)

![](/files/2QtKgPEfq6hxgRm5ujTn)

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