Minimum Operations to Make a Uni-Value Grid

Medium Topics Company Tags

In one operation, add x to one cell of grid or subtract x from one cell. Make all cells equal using as few operations as possible, and return that minimum count. Return -1 if no sequence of operations can make every value equal. The grid is rectangular, and the common final value is your choice.

Example 1:

Minimum Operations to Make a Uni-Value Grid, example 1: illustration of the example

Input: grid = [[1,3],[5,7]]
x = 2

Output: 4

Explanation: Make every cell equal to 3. The values 1, 3, 5, and 7 require 1, 0, 1, and 2 operations respectively, for a total of 4. Choosing 5 also costs 4, and no target costs less.

Example 2:

Minimum Operations to Make a Uni-Value Grid, example 2: illustration of the example

Input: grid = [[2,2],[2,2]]
x = 5

Output: 0

Explanation: Every cell already equals 2, so no operations are needed, regardless of the step size.

Example 3:

Minimum Operations to Make a Uni-Value Grid, example 3: illustration of the example

Input: grid = [[1,2]]
x = 3

Output: -1

Explanation: Adding or subtracting 3 preserves the remainder after division by 3. The two cells have different remainders and can never become equal, so return -1.

Constraints:

  • grid is a nonempty rectangular matrix.
  • Its number of rows and columns are each between 1 and 100000.
  • The total number of cells is at most 100000.
  • 1 <= x, grid[i][j] <= 10000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.