Minimum operations to make product of adjacent element pair of prefix sum negative | 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
function minOperations ( a ) { let res = Number . MAX_VALUE ; let N = a . length ; for ( let r = 0 ; r < 2 ; r ++ ) { let sum = 0 , ans = 0 ; for ( let i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( ( i + r ) % 2 ) { if ( sum <= 0 ) { ans += - sum + 1 ; sum = 1 ; } } else { if ( sum >= 0 ) { ans += sum + 1 ; sum = - 1 ; } } } res = Math . min ( res , ans ) ; } document . write ( res ) ; } let a = [ 1 , - 3 , 1 , 0 ] ; minOperations ( a ) ;