All problems
0613MediumArrayGreedy

Trimming the Parcel Bays

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3914Minimum Operations to Make Array Non Decreasing

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 depot has n bays in a row. Bay i currently holds nums[i] parcels.

One operation takes a single parcel out of one bay and off the site. A bay can never hold a negative number of parcels, and parcels are never added or moved between bays.

The depot passes inspection when the counts read left to right never go down, that is when nums[i] <= nums[i + 1] holds for every neighbouring pair. Return the smallest number of operations that makes the depot pass.

Examples

Example 1

Input
nums = [6, 2, 8, 4]
Output
8

Removing four parcels from bay 0 and four from bay 2 leaves the counts `[2, 2, 4, 4]`, which never go down, for eight operations in total.

Example 2

Input
nums = [1, 3, 6, 9]
Output
0

The counts already rise from left to right, so nothing has to be removed.

Example 3

Input
nums = [5, 4, 1]
Output
7

Taking four parcels from bay 0 and three from bay 1 leaves `[1, 1, 1]`, for seven operations.

Constraints

  • 1 <= n == nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • The answer never exceeds 10^14.

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 min_operations(nums: list[int]) -> int:
Java
public long minOperations(int[] nums)
September 7
Apply