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:
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.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= x, grid[i][j] <= 104
class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
nums = []
m, n = len(grid), len(grid[0])
base = grid[0][0]
for i in range(m):
for j in range(n):
if abs(grid[i][j] - base) % x != 0:
return -1
nums.append(grid[i][j])
nums.sort()
mid = nums[len(nums) >> 1]
ans = 0
for num in nums:
ans += abs(num - mid) // x
return ans
class Solution {
public int minOperations(int[][] grid, int x) {
int m = grid.length, n = grid[0].length;
int[] nums = new int[m * n];
int base = grid[0][0];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (Math.abs(base - grid[i][j]) % x != 0) {
return -1;
}
nums[i * n + j] = grid[i][j];
}
}
Arrays.sort(nums);
int mid = nums[nums.length >> 1];
int ans = 0;
for (int num : nums) {
ans += (Math.abs(num - mid) / x);
}
return ans;
}
}
class Solution {
public:
int minOperations(vector<vector<int>>& grid, int x) {
vector<int> nums;
int m = grid.size(), n = grid[0].size();
int base = grid[0][0];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (abs(grid[i][j] - base) % x != 0) return -1;
nums.push_back(grid[i][j]);
}
}
sort(nums.begin(), nums.end());
int mid = nums[nums.size() >> 1];
int ans = 0;
for (int num : nums) ans += abs(num - mid) / x;
return ans;
}
};
func minOperations(grid [][]int, x int) int {
var nums []int
m, n, base := len(grid), len(grid[0]), grid[0][0]
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if abs(grid[i][j]-base)%x != 0 {
return -1
}
nums = append(nums, grid[i][j])
}
}
sort.Ints(nums)
mid := nums[len(nums)>>1]
ans := 0
for _, num := range nums {
ans += abs(num-mid) / x
}
return ans
}
func abs(x int) int {
if x > 0 {
return x
}
return -x
}