Show problems as
Classic problem #2602MediumArrayBinary SearchSortingPrefix Sum

Minimum Operations to Make All Array Elements Equal

Real-world version: Cost of Bringing Every Gauge to Each Target
Tracked in this browser only
Read Minimum Operations to Make All Array Elements Equal on LeetCode(opens in a new tab)

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

A rail of gauges reads gauges. One turn changes a single gauge by one, up or down.

Each entry of targets asks a separate question, and the rail is never actually changed: how many turns would it take to bring every gauge to that target reading?

Return the answers in the order the questions are asked.

Examples

Example 1

Input
gauges = [1, 2, 3], targets = [2]
Output
[2]

Bringing everything to two costs one turn on the 1, nothing on the 2 and one turn on the 3.

Example 2

Input
gauges = [5], targets = [1, 5, 9]
Output
[4, 0, 4]

A single gauge reading five costs four turns to reach one, nothing to reach five, and four again to reach nine.

Example 3

Input
gauges = [10, 10], targets = [10]
Output
[0]

Both gauges already read the target, so nothing needs turning.

Constraints

  • 1 <= gauges.length <= 10^5
  • 1 <= targets.length <= 10^5
  • 1 <= gauges[i] <= 10^9
  • 1 <= targets[i] <= 10^9

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_operations(gauges: list[int], targets: list[int]) -> list[int]:
Java
public List<Long> minOperations(int[] gauges, int[] targets)