Leetcode 1526 Minimum Number of Increments on Subarrays to Form a Target Array
题意: 给定一个数组例如[1, 2, 3,2,1],每次变化一个区间,让区间里的值+1, 求从[0, 0,0,0,0]到[1, 2, 3,2,1]需要几步
https://www.google.com/search?client=safari&rls=en&q=leetcode+1526&ie=UTF-8&oe=UTF-8
思路:
首先这个数组可以分割成很多过非递增子串,对于每一个非递增子串比如
[3,2,1]需要的步数就是递增子串的开头,那么问题就变成了[3, 2, 1, 2]这种问题(两个非递增子串拼在一起),在1和2之间,我需要补充一个差值,所以问题的答案就是a[0]+累加这个差值
https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/description/
class Solution {
public:int minNumberOperations(vector<int>& target) {int res = target[0];for(int i = 1; i < target.size(); i++) {if(target[i] > target[i-1]) {res += target[i] - target[i-1];}}return res;}
};
时间复杂度O(n),算法复杂度O(1)