Sum of even values and update queries on an array | Function to print the result for every query ; If current element is even ; If element is even then remove it from sum ; If the value becomes even after updating ; Store sum for each query ; Print the result for every query ; Driver code
function BalanceArray ( A , Q ) { var ANS = [ ] ; var i , sum = 0 ; for ( i = 0 ; i < A . length ; i ++ ) if ( A [ i ] % 2 == 0 ) sum = sum + A [ i ] ; for ( i = 0 ; i < Q . length ; i ++ ) { var index = Q [ i ] [ 0 ] ; var value = Q [ i ] [ 1 ] ; if ( A [ index ] % 2 == 0 ) sum = sum - A [ index ] ; A [ index ] = A [ index ] + value ; if ( A [ index ] % 2 == 0 ) sum = sum + A [ index ] ; ANS . push ( sum ) ; } for ( i = 0 ; i < ANS . length ; i ++ ) document . write ( ANS [ i ] + " " ) ; } var A = [ 1 , 2 , 3 , 4 ] ; var Q = [ [ 0 , 1 ] , [ 1 , - 3 ] , [ 0 , - 4 ] , [ 3 , 2 ] ] ; BalanceArray ( A , Q ) ;