KatInterview

Fewest Segment Boosts to Make a Sequence Non-Decreasing

Greedy & IntervalsAuto-graded · 18 test cases
MediumAuto-gradedGreedy & Intervalsdifference-arraygreedyarrays

Last updated

Compute the minimum number of +1 contiguous-segment updates needed to make an array non-decreasing, using adjacent differences and a lower-bound argument.

Fewest Segment Boosts

You are given a list values of n integers. In one boost, you pick any contiguous segment of the list (from position l to position r, with 0 <= l <= r < n) and add exactly 1 to every element in that segment. Each boost costs 1, no matter how long the segment is.

You may perform as many boosts as you like, and segments may overlap or repeat. Your goal is to make the list non-decreasing, meaning values[i] <= values[i + 1] for every valid i.

Return the minimum number of boosts needed. If the list is already non-decreasing (including when it has a single element), return 0.

Only boosts (adding 1) are allowed; elements can never be decreased.

Function

Implement min_segment_boosts(values), which takes the list of integers and returns a single integer: the minimum number of boosts.

Constraints

  • 1 <= n <= 10^5
  • 0 <= values[i] <= 10^9
  • The answer can be as large as about 10^14, so make sure your arithmetic does not overflow in languages with fixed-width integers.

Examples

Example 1

Input: min_segment_boosts([3, 2, 1])

Output: 2

Example 2

Input: min_segment_boosts([1, 2, 3])

Output: 0

Hints

Hint 1

Think about the differences between neighbours, d[i] = values[i] - values[i-1]. The list is non-decreasing exactly when all of these are at least 0.

Hint 2

A boost on [l, r] changes only two differences: d[l] goes up by 1 and d[r+1] goes down by 1 (if r+1 exists). Which differences can a boost actually help?

Hint 3

Each negative difference at position i can only be raised by boosts that start at i, so you need at least its deficit in boosts there. Show that boosting the suffix starting at i achieves this without hurting any other difference.