[LeetCode] Minimum Operations to Make a Uni-Value Grid

2033. Minimum Operations to Make a Uni-Value Grid

You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.

A uni-value grid is a grid where all the elements of it are equal.

Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minOperations(vector<vector<int>>& A, int x) {
vector<int> B;
int res = 0;
for(auto& row : A) for(auto& col : row) B.push_back(col);
sort(begin(B), end(B));
int median = B[B.size() / 2];
for(auto& b : B) {
int diff = abs(b-median);
if(diff % x) return -1;
res += diff / x;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/08/PS/LeetCode/minimum-operations-to-make-a-uni-value-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.