Show problems as
Classic problem #2033MediumArrayMathSortingMatrix

Minimum Operations to Make a Uni-Value Grid

Real-world version: Levelling A Bench Of Stepped Dials
Tracked in this browser only
Read Minimum Operations to Make a Uni-Value Grid on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A test bench carries a rectangular block of dials. grid[i][j] is the setting the dial in row i, column j currently shows.

One adjustment picks a single dial and either raises its setting by exactly step or lowers it by exactly step. Nothing else can change a dial. A setting is free to pass below zero or above its starting value along the way.

The bench is level when every dial shows the same setting. Return the fewest adjustments that leave the bench level, or -1 when no sequence of adjustments can level it.

Examples

Example 1

Input
grid = [[3, 7, 11], [15, 19, 23]], step = 4
Output
9

Bring every dial to 15. The 3 takes three raises, the 7 takes two, the 11 takes one, the 15 takes none, the 19 takes one lowering and the 23 takes two, which is 3 + 2 + 1 + 0 + 1 + 2 = 9 adjustments.

Example 2

Input
grid = [[6, 7]], step = 3
Output
-1

From 6 the reachable settings are `..., 0, 3, 6, 9, 12, ...` and from 7 they are `..., 1, 4, 7, 10, 13, ...`. The two dials share no reachable setting, so the bench cannot be levelled.

Example 3

Input
grid = [[2, 2], [2, 8]], step = 2
Output
3

Three lowerings of 2 turn the 8 into a 2, and the other three dials already show 2.

Constraints

  • 1 <= grid.length <= 10^5
  • 1 <= grid[i].length <= 10^5
  • 1 <= grid.length * grid[i].length <= 10^5, so the bench holds at most 10^5 dials.
  • 1 <= step <= 10^4
  • 1 <= grid[i][j] <= 10^4
  • Every row of grid has the same length.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def min_adjustments(grid: list[list[int]], step: int) -> int:
Java
public int minAdjustments(int[][] grid, int step)