Minimum Operations to Make a Uni-Value Grid
Real-world version: Levelling A Bench Of Stepped DialsThe 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.
def min_adjustments(grid: list[list[int]], step: int) -> int:public int minAdjustments(int[][] grid, int step)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Get Biggest Three Rhombus Sums in a GridReal-world version: Three Best Diamond Outlines on a BoardMedium
- Best Meeting PointReal-world version: Where to Set the Muster PointHard
- Maximum Product of Three NumbersReal-world version: Largest Triple DriftEasy
- Missing NumberReal-world version: Unclaimed Badge NumberEasy