#2033
Minimum Operations to Make a Uni-Value Grid
specialist · 600 · lc medium +29 · verified · 67.5% accepted · 1,109 likes · top 74%
Description
You have an m x n integer grid and an integer x. Each operation adds or subtracts x from any single cell. A uni-value grid has all cells equal. Return the fewest operations needed to make grid uni-value, or -1 if it is impossible.
Example 1:
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:
Input: grid = [[1,5],[2,3]], x = 1
Output: 5
Explanation: We can make every element equal to 3.
Example 3:
Input: grid = [[1,2],[3,4]], x = 2
Output: -1
Explanation: It is impossible to make every element equal.
Code
1
2
3