Replace all elements by difference of sums of positive and negative numbers after that element | Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; calculate difference of both sums ; if i - th element is positive , add it to positive sum ; if i - th element is negative , add it to negative sum ; replace i - th elements with absolute difference ; Driver Code
function printArray ( N , arr ) { for ( var i = 0 ; i < N ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ; } function replacedArray ( N , arr ) { var pos_sum , neg_sum , i , j , diff ; pos_sum = 0 ; neg_sum = 0 ; for ( i = N - 1 ; i >= 0 ; i -- ) { diff = Math . abs ( pos_sum ) - Math . abs ( neg_sum ) ; if ( arr [ i ] > 0 ) pos_sum += arr [ i ] ; else neg_sum += arr [ i ] ; arr [ i ] = Math . abs ( diff ) ; } } var N = 5 ; var arr = [ 1 , - 1 , 2 , 3 , - 2 ] ; replacedArray ( N , arr ) ; printArray ( N , arr ) ; N = 6 ; var arr1 = [ - 3 , - 4 , - 2 , 5 , 1 , - 2 ] ; replacedArray ( N , arr1 ) ; printArray ( N , arr1 ) ;