1144. Decrease Elements To Make Array Zigzag LeetCode Solution
In this guide, you will get 1144. Decrease Elements To Make Array Zigzag LeetCode Solution with the best time and space complexity. The solution to Decrease Elements To Make Array Zigzag problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Decrease Elements To Make Array Zigzag solution in C++
- Decrease Elements To Make Array Zigzag solution in Java
- Decrease Elements To Make Array Zigzag solution in Python
- Additional Resources
Problem Statement of Decrease Elements To Make Array Zigzag
Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.
An array A is a zigzag array if either:
Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] A[3] …
OR, every odd-indexed element is greater than adjacent elements, ie. A[0] A[2] A[4] < …
Return the minimum number of moves to transform the given array nums into a zigzag array.
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
Complexity Analysis
- Time Complexity:
- Space Complexity:
1144. Decrease Elements To Make Array Zigzag LeetCode Solution in C++
class Solution {
public:
int movesToMakeZigzag(vector<int>& nums) {
vector<int> decreasing(2);
for (int i = 0; i < nums.size(); ++i) {
int l = i > 0 ? nums[i - 1] : 1001;
int r = i + 1 < nums.size() ? nums[i + 1] : 1001;
decreasing[i % 2] += max(0, nums[i] - min(l, r) + 1);
}
return min(decreasing[0], decreasing[1]);
}
};
/* code provided by PROGIEZ */
1144. Decrease Elements To Make Array Zigzag LeetCode Solution in Java
class Solution {
public int movesToMakeZigzag(int[] nums) {
int[] decreasing = new int[2];
for (int i = 0; i < nums.length; ++i) {
int l = i > 0 ? nums[i - 1] : 1001;
int r = i + 1 < nums.length ? nums[i + 1] : 1001;
decreasing[i % 2] += Math.max(0, nums[i] - Math.min(l, r) + 1);
}
return Math.min(decreasing[0], decreasing[1]);
}
}
// code provided by PROGIEZ
1144. Decrease Elements To Make Array Zigzag LeetCode Solution in Python
class Solution:
def movesToMakeZigzag(self, nums: list[int]) -> int:
decreasing = [0] * 2
for i, num in enumerate(nums):
l = nums[i - 1] if i > 0 else 1001
r = nums[i + 1] if i + 1 < len(nums) else 1001
decreasing[i % 2] += max(0, num - min(l, r) + 1)
return min(decreasing[0], decreasing[1])
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.