- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Decrease Elements To Make Array Zigzag in Python
Suppose we have an array nums of integers, a move operation is actually choosing any element and decreasing it by 1. An array A is a zigzag array if either 1 or 2 is satisfied −
Every even-indexed element is greater than adjacent elements, So. A[0] > A[1] < A[2] > A[3] < A[4] > ... and so on.
Every odd-indexed element is greater than adjacent elements, So. A[0] < A[1] > A[2] < A[3] > A[4] < ... and so on.
We have to find the minimum number of moves to transform the given array nums into a zigzag array.
So if the array is like [1,2,3], then the output will be 2, as we can decrease 2 to 0 or 3 to 1
To solve this, we will follow these steps −
Define a method called solve(), this will take nums and start, this will work as below −
k := 0
for i in range start to length of nums, increase by 2
left := 100000 when i – 1 < 0, otherwise nums[i - 1]
right := 100000 when i + 1 >= length of nums, otherwise nums[i + 1]
temp := (minimum of left and right) – 1 – nums[i]
if temp < 0, then k := k + |temp|
return k
In the main method, it will be
ans := solve(nums, 0)
ans := minimum of ans and solve(nums, 1)
return ans
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def solve(self,nums,start): k = 0 for i in range(start,len(nums),2): left = 100000 if i-1<0 else nums[i-1] right = 10000 if i+1>=len(nums) else nums[i+1] temp= (min(left,right)-1 - nums[i]) if temp<0: k+=abs(temp) return k def movesToMakeZigzag(self, nums): ans = self.solve(nums,0) ans = min(ans,self.solve(nums,1)) return ans ob = Solution() print(ob.movesToMakeZigzag([1,2,3]))
Input
[1,2,3]
Output
2