題目: LeetCode - 1526. Minimum Number of Increments on Subarrays to Form a Target Array

題目說明

給一個陣列 target,求一個同等大小,元素值為 0 的陣列,建成 target 那樣需要建造幾層。

解題思路

想像成是在爬山,只有在走上坡的時候才需要建造,走下坡時因為上坡已經建過了所以就不用再建。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// fast IO
static auto __ = []()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
class Solution {
public:
int minNumberOperations(vector<int>& target) {
int res = 0, pre = 0;
for(auto i : target)
{
if(i > pre)
res += i - pre;
pre = i;
}
return res;
}
};