human
Minimum increment / decrement operations required on Array to satisfy given conditions | Function to find minimum number of operations to get desired array.
For odd ' i ' , sum of elements till ' i ' is positive.
If i is even and sum is positive , make it negative by subtracting 1 + | s | from a [ i ].
If i is odd and sum is negative , make it positive by adding 1 + | s | into a [ i ].
For odd ' i ' , sum of elements till ' i ' is negative.
Check if ' i ' is odd and sum is positive , make it negative by subtracting 1 + | s | from a [ i ].
Check if ' i ' is even and sum is negative , make it positive by adding 1 + | s | into a [ i ].
Return the minimum of the two.
Driver Code.
Given array arr [ ].
Function call"
How can the above be solved in Python?
assistant
#Here is code to minimum increment / decrement operations required on Array to satisfy given conditions and the other steps required.
 def minOperations ( a , N ) :
	num_of_ops1 = num_of_ops2 = sum = 0 ;
	for i in range ( N ) :
		sum += a [ i ]
		if ( i % 2 == 0 and sum >= 0 ) :
			num_of_ops1 += ( 1 + abs ( sum ) )
			sum = - 1
		elif ( i % 2 == 1 and sum <= 0 ) :
			num_of_ops1 += ( 1 + abs ( sum ) )
			sum = 1
	sum = 0
	for i in range ( N ) :
		sum += a [ i ]
		if ( i % 2 == 1 and sum >= 0 ) :
			num_of_ops2 += ( 1 + abs ( sum ) )
			sum = - 1
		elif ( i % 2 == 0 and sum <= 0 ) :
			num_of_ops2 += ( 1 + abs ( sum ) )
			sum = 1
	return min ( num_of_ops1 , num_of_ops2 )
if __name__ == " _ _ main _ _ " :
	arr = [ 3 , - 4 , 5 , 0 , 1 ]
	N = len ( arr )
	print ( minOperations ( arr , N ) )