[LeetCode] Minimum Operations to Make Array Non Decreasing

3914. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
long long minOperations(vector<int>& nums) {
long long res = 0, prv = 0, pre = 0;
for(auto& n : nums) {
if(n + pre < prv) {
int diff = prv - (n + pre);
pre += diff;
res += diff;
}
prv = n + pre;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-operations-to-make-array-non-decreasing/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.