Minimum Operations to Make Array Equal to Target
Real-world version: Nudging a Bank of Sliders into PlaceThe statement here is our own: the same inputs, outputs and technique.
A mixing desk carries a row of sliders. levels[i] is the notch the i-th slider sits on and wanted[i] is the notch it should sit on.
In one gang move you pick a run of neighbouring sliders and either raise every slider in that run by one notch or lower every slider in that run by one notch. A run may be a single slider.
Return the fewest gang moves that bring every slider onto the notch it should sit on.
Examples
Example 1
- Input
- levels = [2, 2, 2], wanted = [3, 4, 3]
- Output
- 2
The shortfalls are one, two and one notch, all upward. One move raises all three sliders and a second raises the middle slider alone.
Example 2
- Input
- levels = [4, 1], wanted = [1, 4]
- Output
- 6
The first slider has to drop three notches and the second has to climb three, and no run serves both directions, so each is worked on its own.
Example 3
- Input
- levels = [1, 1, 1], wanted = [2, 1, 2]
- Output
- 2
The middle slider is already in place, which splits the row. A run covering all three would push it off its notch, so the outer two are raised separately.
Constraints
- 1 <= levels.length <= 10^5
- levels.length == wanted.length
- 1 <= levels[i] <= 10^8
- 1 <= wanted[i] <= 10^8
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 minimum_operations(levels: list[int], wanted: list[int]) -> int:public long minimumOperations(int[] levels, int[] wanted)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 16 test cases: 16 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
- Minimum Number of Increments on Subarrays to Form a Target ArrayReal-world version: Sealant Runs Along a TowpathHard
- Sum of Subarray MinimumsReal-world version: Weakest Reading Per StretchMedium
- Shortest Unsorted Continuous SubarrayReal-world version: Shortest Stretch to Re-sortMedium
- Max Chunks To Make SortedReal-world version: Most Blocks a Line Can Be Cut IntoMedium