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.
Input: grid = [[2,4],[6,8]], x = 2Output: 4Explanation: 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.
Input: grid = [[1,5],[2,3]], x = 1Output: 5Explanation: We can make every element equal to 3.
Input: grid = [[1,2],[3,4]], x = 2Output: -1Explanation: It is impossible to make every element equal.
class Solution: # Time: O(m*n log(m*n)) # Space: O(m*n) def min_operations(self, grid: list[list[int]], x: int) -> int: vals = [v for row in grid for v in row] rem = vals[0] % x if any(v % x != rem for v in vals): return -1 vals.sort() median = vals[len(vals) // 2] return sum(abs(v - median) // x for v in vals)