Minimum Operations to Make a Uni-Value Grid

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
2 4
6 8
Inputgrid = [[2,4],[6,8]], x = 2
Output4
We can make every element equal to 4 using 4 total operations: add x to 2 once, subtract x from 6 once, and subtract x from 8 twice.
Example 2
1 5
2 3
Inputgrid = [[1,5],[2,3]], x = 1
Output5
We can make every element equal to 3 in 5 operations.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10^5
  • 1 <= m * n <= 10^5
  • 1 <= x, grid[i][j] <= 10^4

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate