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
def minOperations ( a , N ) : NEW_LINE INDENT num_of_ops1 = num_of_ops2 = sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( i % 2 == 0 and sum >= 0 ) : NEW_LINE INDENT num_of_ops1 += ( 1 + abs ( sum ) ) NEW_LINE sum = - 1 NEW_LINE DEDENT elif ( i % 2 == 1 and sum <= 0 ) : NEW_LINE INDENT num_of_ops1 += ( 1 + abs ( sum ) ) NEW_LINE sum = 1 NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( i % 2 == 1 and sum >= 0 ) : NEW_LINE INDENT num_of_ops2 += ( 1 + abs ( sum ) ) NEW_LINE sum = - 1 NEW_LINE DEDENT elif ( i % 2 == 0 and sum <= 0 ) : NEW_LINE INDENT num_of_ops2 += ( 1 + abs ( sum ) ) NEW_LINE sum = 1 NEW_LINE DEDENT DEDENT return min ( num_of_ops1 , num_of_ops2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , - 4 , 5 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N ) ) NEW_LINE DEDENT