You are given an m x n integer grid and an integer x. In one operation you can add x to or subtract x from any one element. A uni-value grid is one where every element is equal. Return the minimum number of operations needed to make the grid uni-value, or -1 if it is impossible.
You are given an m x n integer grid and an integer x. In one operation you can add x to or subtract x from any one element. A uni-value grid is one where every element is equal. Return the minimum number of operations needed to make the grid uni-value, or -1 if it is impossible.
Example 1:
Input: {"grid":[[2,4],[6,8]],"x":2}
Output: 4
Constraints:
m==grid.length
n==grid[i].length
1≤m,n≤105
1≤m⋅n≤105
1≤x,grid[i][j]≤104
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"grid":[[2,4],[6,8]],"x":2}
One operation adds or subtracts x = 2 from a single cell. Every cell must end on the same value, using as few operations as possible.
grid
2
4
6
8
number line
Values appear here once the grid is flattened and sorted.