Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Decrease Elements To Make Array Zigzag in Python
Suppose we have an array of integers, where a move operation involves choosing any element and decreasing it by 1. An array is a zigzag array if it satisfies either of these patterns:
Every even-indexed element is greater than adjacent elements: A[0] > A[1] A[3] ... and so on.
Every odd-indexed element is greater than adjacent elements: A[0] A[2] A[4]
We need to find the minimum number of moves to transform the given array into a zigzag array.
Algorithm Approach
The strategy is to try both zigzag patterns and choose the one requiring fewer moves:
Pattern 1: Make even-indexed elements greater than their neighbors
Pattern 2: Make odd-indexed elements greater than their neighbors
For each pattern, we decrease elements at specific positions to ensure they are smaller than their neighbors.
Implementation
class Solution:
def solve(self, nums, start):
moves = 0
for i in range(start, len(nums), 2):
# Get left and right neighbors (use large value if out of bounds)
left = float('inf') if i - 1 < 0 else nums[i - 1]
right = float('inf') if i + 1 >= len(nums) else nums[i + 1]
# Calculate how much we need to decrease current element
min_neighbor = min(left, right)
if nums[i] >= min_neighbor:
moves += nums[i] - min_neighbor + 1
return moves
def movesToMakeZigzag(self, nums):
# Try making even indices peaks, then odd indices peaks
even_peaks = self.solve(nums, 0) # Start from index 0 (even)
odd_peaks = self.solve(nums, 1) # Start from index 1 (odd)
return min(even_peaks, odd_peaks)
# Test the solution
solution = Solution()
test_array = [1, 2, 3]
result = solution.movesToMakeZigzag(test_array)
print(f"Input: {test_array}")
print(f"Minimum moves required: {result}")
Input: [1, 2, 3] Minimum moves required: 2
How It Works
For the array [1, 2, 3]:
Pattern 1 (even indices as peaks): We need to make indices 0 and 2 greater than their neighbors. Since 1 2, we need 2 moves to decrease element at index 1.
Pattern 2 (odd indices as peaks): We need index 1 to be greater than neighbors. Since 2 > 1 but 2
Both patterns require 2 moves, so the answer is 2.
Example with Different Array
# Test with another example
solution = Solution()
test_array = [9, 6, 1, 6, 2]
result = solution.movesToMakeZigzag(test_array)
print(f"Input: {test_array}")
print(f"Minimum moves required: {result}")
Input: [9, 6, 1, 6, 2] Minimum moves required: 4
Conclusion
The zigzag array problem is solved by testing both possible zigzag patterns and choosing the one requiring fewer moves. We systematically check elements at alternating positions and calculate the minimum decreases needed to satisfy the zigzag condition.
---