Minimum operations to make product of adjacent element pair of prefix sum negative | Java code for the above approach ; Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the value of sum ; Check if i + r is odd ; Check if prefix sum is not positive ; Update the value of ans and sum ; Check if prefix sum is not negative ; Update the value of ans and sum ; Update the value of res ; Print the value of res ; Driver Code
import java . util . * ; class GFG { static void minOperations ( ArrayList < Integer > a ) { int res = Integer . MAX_VALUE ; int N = a . size ( ) ; for ( int r = 0 ; r < 2 ; r ++ ) { int sum = 0 , ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a . get ( i ) ; if ( ( i + r ) % 2 == 1 ) { if ( sum <= 0 ) { ans += - sum + 1 ; sum = 1 ; } } else { if ( sum >= 0 ) { ans += sum + 1 ; sum = - 1 ; } } } res = Math . min ( res , ans ) ; } System . out . print ( res ) ; } public static void main ( String args [ ] ) { ArrayList < Integer > a = new ArrayList < Integer > ( ) ; a . add ( 1 ) ; a . add ( - 3 ) ; a . add ( 1 ) ; a . add ( 0 ) ; minOperations ( a ) ; } }