Minimum increment / decrement operations required on Array to satisfy given conditions | Java program for the above approach ; 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
import java . util . * ; class GFG { static int minOperations ( int a [ ] , int N ) { int num_of_ops1 , num_of_ops2 , sum ; num_of_ops1 = num_of_ops2 = sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( i % 2 == 0 && sum >= 0 ) { num_of_ops1 += ( 1 + Math . abs ( sum ) ) ; sum = - 1 ; } else if ( i % 2 == 1 && sum <= 0 ) { num_of_ops1 += ( 1 + Math . abs ( sum ) ) ; sum = 1 ; } } sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( i % 2 == 1 && sum >= 0 ) { num_of_ops2 += ( 1 + Math . abs ( sum ) ) ; sum = - 1 ; } else if ( i % 2 == 0 && sum <= 0 ) { num_of_ops2 += ( 1 + Math . abs ( sum ) ) ; sum = 1 ; } } return Math . min ( num_of_ops1 , num_of_ops2 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , - 4 , 5 , 0 , 1 } ; int N = arr . length ; System . out . print ( minOperations ( arr , N ) ) ; } }