-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem-1144.cpp
29 lines (26 loc) · 1.04 KB
/
Problem-1144.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Problem - 1144
// O(n) time complexity and O(1) space solution
// https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/
class Solution {
public:
int movesToMakeZigzag(vector<int>& nums) {
if(nums.size() <= 2)
return 0;
int a = 0, b = 0;
for(int i = 1; i < nums.size(); i += 2) {
if (i < nums.size()-1 && (nums[i] >= nums[i-1] || nums[i] >= nums[i+1]))
a += nums[i] - min(nums[i-1], nums[i+1]) + 1;
else if(i+1 >= nums.size() && nums[i] >= nums[i-1])
a += nums[i] - nums[i-1] + 1;
}
for(int i = 0; i < nums.size(); i += 2) {
if (i == 0 && nums[i] >= nums[i+1])
b += nums[i] - nums[i+1] + 1;
else if(i !=0 && i < nums.size()-1 && (nums[i] >= nums[i-1] || nums[i] >= nums[i+1]))
b += nums[i] - min(nums[i-1], nums[i+1]) + 1;
else if(i+1 >= nums.size() && nums[i] >= nums[i-1])
b += nums[i] - nums[i-1] + 1;
}
return min(a, b);
}
};