2160 Minimum Operations To Make A Uni Value Grid
2160 Minimum Operations To Make A Uni Value Grid
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.
Example 1:
1
2
3
4
5
6
7
8
9
**Input:** grid = [[2,4],[6,8]], x = 2
**Output:** 4
**Explanation:** We can make every element equal to 4 by doing the following:
- Add x to 2 once.
- Subtract x from 6 once.
- Subtract x from 8 twice.
A total of 4 operations were used.
Example 2:
1
2
3
4
5
**Input:** grid = [[1,5],[2,3]], x = 1
**Output:** 5
**Explanation:** We can make every element equal to 3.
Example 3:
1
2
3
4
5
**Input:** grid = [[1,2],[3,4]], x = 2
**Output:** -1
**Explanation:** It is impossible to make every element equal.
Constraints:
1
2
3
4
5
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= x, grid[i][j] <= 104
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::cmp::min;
use std::collections::HashSet;
impl Solution {
pub fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 {
/* its always apossible ? No ,shortest path is just step behind
many destinations ?
maybe mmost frequent element is an unique number
one of the number from array is unique number
grid is not relevant ? it could be an array ?
could binary search be possible ?
we search for ans ?
sum(arr) + knx // m is an integer ?
m0st promising is choose each number from gid
then find the diff between then
[2,4,6,8] -> [4,4,4,4] 16-12 = 4 which means 2x
[2,0,2,2*2] // not this does not work as plus 2 and -2 are eaten by each other and we never find ans
given that 10000 is the limit of
choose 1 to 10K
for each select and element as answer and perform the op on array ?
*/
let mut hs = HashSet::new();
let mut a = 0;
let mut new_arr = Vec::new();
for arr in grid.clone(){
for j in arr {
new_arr.push(j);
a = j;
hs.insert(a);
}
}
if new_arr.len() == 1 {
return 0;
}
new_arr.sort();
let dest = new_arr[new_arr.len() / 2];
let mut res = 10000000;
let mut temp = 0;
let mut invalid = false;
for j in new_arr.clone(){
//print!("{} {} {}\n", k as i32,j,x);
if ((dest - j) % x != 0) {
temp = 10000000;
break;
}
temp += ((dest - j) / x).abs();
}
res = temp;
//print!("{}\n", temp as i32);
if res == 10000000 {
return -1;
}
return res;
}
}
This post is licensed under CC BY 4.0 by the author.


