Minimum increments or decrements required to signs of prefix sum array elements alternating | Function to find the minimum number of increments / decrements of array elements by 1 to make signs of prefix sum array elements alternating ; Case 1. neg - pos - neg ; Stores the current sign of the prefix sum of array ; Stores minimum number of operations for Case 1 ; Traverse the array ; Checking both conditions ; Update the current prefix1 to currentPrefixSum ; Case 2. pos - neg - pos ; Stores the prefix sum of array ; Stores minimum number of operations for Case 1 ; Checking both conditions ; Update the current prefix2 to currentPrefixSum ; Driver Code
function minimumOperations ( A , N ) { let cur_prefix_1 = 0 ; let parity = - 1 ; let minOperationsCase1 = 0 ; for ( let i = 0 ; i < N ; i ++ ) { cur_prefix_1 += A [ i ] ; if ( cur_prefix_1 == 0 parity * cur_prefix_1 < 0 ) { minOperationsCase1 += Math . abs ( parity - cur_prefix_1 ) ; cur_prefix_1 = parity ; } parity *= - 1 ; } let cur_prefix_2 = 0 ; parity = 1 ; let minOperationsCase2 = 0 ; for ( let i = 0 ; i < N ; i ++ ) { cur_prefix_2 += A [ i ] ; if ( cur_prefix_2 == 0 parity * cur_prefix_2 < 0 ) { minOperationsCase2 += Math . abs ( parity - cur_prefix_2 ) ; cur_prefix_2 = parity ; } parity *= - 1 ; } return Math . min ( minOperationsCase1 , minOperationsCase2 ) ; } let A = [ 1 , - 3 , 1 , 0 ] ; let N = A . length ; document . write ( minimumOperations ( A , N ) ) ;