递减元素使数组呈锯齿状【LC1144】
给你一个整数数组
nums
,每次 操作 会从中选择一个元素并 将该元素的值减少 1。如果符合下列情况之一,则数组
A
就是 锯齿数组:
- 每个偶数索引对应的元素都大于相邻的元素,即
A[0] > A[1] < A[2] > A[3] < A[4] > ...
- 或者,每个奇数索引对应的元素都大于相邻的元素,即
A[0] < A[1] > A[2] < A[3] > A[4] < ...
返回将数组
nums
转换为锯齿数组所需的最小操作次数。
-
思路:贪心+枚举
由于每次操作只能将一个元素减小1,因此我们可以统计所有奇数索引以及所有偶数索引小于相邻元素的总操作数,那么最终结果为两者的较小值。对于
nums[i]
,需要减小的值为Math.max(nums[i]−nums[i−1],nums[i]−nums[i+1])Math.max(nums[i]-nums[i-1],nums[i]-nums[i+1])Math.max(nums[i]−nums[i−1],nums[i]−nums[i+1])【贪心】,如果该值小于0,那么无需进行操作 -
实现
class Solution { public int movesToMakeZigzag(int[] nums) { int a = 0, b = 0; int n = nums.length; if (n == 1) return 0; for (int i = 0; i < n; i++){ int count = 0; if (i - 1 >= 0){ count = Math.max(nums[i] - nums[i - 1] + 1, count); } if (i + 1 < n){ count = Math.max(nums[i] - nums[i + 1] + 1, count); } if ((i & 1 )== 0){// 偶数 a += count; }else{// 奇数 b += count; } } return Math.min(a, b); } }
- 复杂度
- 时间复杂度:O(n)O(n)O(n)
- 空间复杂度:O(1)O(1)O(1)
- 复杂度