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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/math/2033.-minimum-operations-to-make-a-uni-value-grid.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
