---
# System prepended metadata

title: 2033. Minimum Operations to Make a Uni-Value Grid
tags: [Leetcode, Medium, Math]

---

# 2033. Minimum Operations to Make a Uni-Value Grid
###### tags: `Leetcode` `Medium` `Math`
Link: https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/
## 思路
首先找中位数，如果每个数和中位数的差都能被x整除，就可以变成unique number
Proof can be found [here](https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1513518/Prove-the-median-answer).
## Code
```java=
class Solution {
    public int minOperations(int[][] grid, int x) {
        int m = grid.length;
        int n = grid[0].length;
        int[] nums = new int[m*n];
        int idx = 0;
        
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                nums[idx++] = grid[i][j];        
            }
        }
        
        Arrays.sort(nums);
        
        int ans = 0;
        
        for(int i = 0;i < nums.length;i++){
            if((nums[i]-nums[nums.length/2])%x==0){
                ans += Math.abs((nums[i]-nums[nums.length/2])/x);
            }
            else{
                return -1;
            }
        }
        return ans;
    }
}
```