Array sum after replacing all occurrences of X by Y for Q queries | Function that print the sum of the array for Q queries ; Stores the frequencies of array elements ; Calculate the sum of the initial array and store the frequency of each element in map ; Iterate for all the queries ; Store query values ; Decrement the sum accordingly ; Increment the sum accordingly ; Set count of Y [ i ] ; Reset count of X [ i ] ; Print the sum ; Driver Code ; Function call
function sumOfTheArrayForQuery ( A , N , X , Y , Q ) { var sum = 0 ; var count = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( count . has ( A [ i ] ) ) count . set ( A [ i ] , count . get ( A [ i ] ) + 1 ) else count . set ( A [ i ] , 1 ) } for ( var i = 0 ; i < Q ; i ++ ) { var x = X [ i ] , y = Y [ i ] ; if ( count . has ( X [ i ] ) ) { sum -= count . get ( X [ i ] ) * X [ i ] ; sum += count . get ( X [ i ] ) * Y [ i ] ; } if ( count . has ( Y [ i ] ) ) { count . set ( Y [ i ] , count . get ( Y [ i ] ) + count . get ( X [ i ] ) ) ; } count . set ( X [ i ] , 0 ) ; document . write ( sum + " " ) ; } } var arr = [ 1 , 2 , 1 , 3 , 2 ] ; var X = [ 2 , 3 , 5 ] ; var Y = [ 3 , 1 , 2 ] ; var N = arr . length ; var Q = X . length ; sumOfTheArrayForQuery ( arr , N , X , Y , Q ) ;