[LeetCode] Minimum Number of Increments on Subarrays to Form a Target Array

1526. Minimum Number of Increments on Subarrays to Form a Target Array

You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.

In one operation you can choose any subarray from initial and increment each value by one.

Return the minimum number of operations to form a target array from initial.

The test cases are generated so that the answer fits in a 32-bit integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int minNumberOperations(vector<int>& target) {
vector<int> st;
int res = 0, n = target.size();
for(int i = 0; i < n; i++) {
if(st.empty()) {
st.push_back(target[i]);
res += target[i];
} else if(st.back() < target[i]) {
res += target[i] - st.back();
st.push_back(target[i]);
} else if(st.back() > target[i]) {
st.erase(lower_bound(st.begin(), st.end(), target[i]), st.end());
st.push_back(target[i]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/24/PS/LeetCode/minimum-number-of-increments-on-subarrays-to-form-a-target-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.