Mid/SeniorArrayGreedy

Minimum Operations to Make Array Non Decreasing

You are given an integer array nums of length n.

In one operation, you may choose any subarray nums[l..r] and increase each element in that subarray by x, where x is any positive integer.

Return the minimum possible sum of the values of x across all operations required to make the array non-decreasing.

An array is non-decreasing if nums[i] <= nums[i + 1] for all 0 <= i < n - 1.

Example 1
Inputnums = [3,3,2,1]
Output2
Choosing subarrays [2..3] and [3..3] with x = 1 each makes the array [3, 3, 3, 3], so the total sum is 2.
Example 2
Inputnums = [5,1,2,3]
Output4
Choosing subarray [1..3] with x = 4 makes the array [5, 5, 6, 7], so the total sum is 4.

Constraints

  • 1 <= n == nums.length <= 10^5
  • 1 <= nums[i] <= 10^9

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate