All problems
1188HardArrayDynamic ProgrammingStackGreedyMonotonic Stack

Nudging a Bank of Sliders into Place

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3229Minimum Operations to Make Array Equal to Target

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def minimum_operations(levels: list[int], wanted: list[int]) -> int:
Java
public long minimumOperations(int[] levels, int[] wanted)
September 7
Apply