1144. Decrease Elements To Make Array Zigzag

问题:

给定一个数组,使用对数组元素减-1的方式,使得数组成为一个zigzag锯形数组。

求最少减的数量

Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation: We can decrease 2 to 0 or 3 to 1.

Example 2:
Input: nums = [9,6,1,6,2]
Output: 4
 
Constraints:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000

  

解法:

2种可能:

对数组的

奇数位减少:使得该位的left和right>自己

偶数位减少:使得该位的left和right>自己

那么只需要取,该位为:min( left, right )-1

那么该位的减少量=nums[i]-min( left, right )+1

但如果该位本身就比left和right都要小,那么该位其实已经满足锯形的情况,值不需要减少。

 

代码参考:

 1 class Solution {
 2 public:
 3     int movesToMakeZigzag(vector<int>& nums) {
 4         int res[2]={0};
 5         int left=0, right=0;
 6         for(int i=0; i<nums.size(); i++){
 7             left=(i>0)?nums[i-1]:1001;
 8             right=(i<nums.size()-1)?nums[i+1]:1001;
 9             res[i%2]+=max(0, nums[i]-min(left,right)+1);
10         }
11         return min(res[0], res[1]);
12     }
13 };

 


⚠️ 注意:只能对元素进行减操作

因此,原先想到的方法不适用:

原先的方法为:

该题的最终锯形数组:只有初始为增,或者初始为减,两种情况

那么对这两种情况分类讨论,后一个数比前一个数大1,或小1,这样累计得出。

比如对测试case:[10, 4,4,10,10,6,2,3]

原先的方法:则有 [10,11,4,10,9,10,2,3]

//diff:[ 0, 7,0, 0,1, 4, 0, 0]=12

小于,符合题意的方法:

奇数位减少:[3, 4,3,10,5,6,2,3]
//diff:[7, 0,1, 0,5,0,0,0]=13

or

偶数位减少:[10, 3,4, 3,10,1,2,1]
//diff:[0, 1,0, 7,0 ,5,0,2]=15

但不符合题意的只能做减操作,因此不行。

posted @ 2020-06-14 14:32  habibah_chang  阅读(149)  评论(0编辑  收藏  举报