Array sum after replacing all occurrences of X by Y for Q queries | C # implementation to find the sum of the array for the given Q queries ; Function that print the sum of the array for Q queries ; Stores the frequencies of array elements Create an empty hash map ; 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
using System ; using System . Collections . Generic ; class GFG { public static void sumOfTheArrayForQuery ( int [ ] A , int N , int [ ] X , int [ ] Y , int Q ) { int sum = 0 ; Dictionary < int , int > count = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( count . ContainsKey ( A [ i ] ) ) { count [ A [ i ] ] = count [ A [ i ] ] + 1 ; } else { count . Add ( A [ i ] , 1 ) ; } } for ( int i = 0 ; i < Q ; i ++ ) { int x = X [ i ] , y = Y [ i ] ; if ( count . ContainsKey ( X [ i ] ) ) { sum -= count [ X [ i ] ] * X [ i ] ; sum += count [ X [ i ] ] * Y [ i ] ; } if ( count . ContainsKey ( Y [ i ] ) && count . ContainsKey ( X [ i ] ) ) { count [ Y [ i ] ] = count [ Y [ i ] ] + count [ X [ i ] ] ; } if ( count . ContainsKey ( X [ i ] ) ) { count [ X [ i ] ] = 0 ; } Console . Write ( sum + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 1 , 3 , 2 } ; int [ ] X = { 2 , 3 , 5 } ; int [ ] Y = { 3 , 1 , 2 } ; int N = arr . Length ; int Q = X . Length ; sumOfTheArrayForQuery ( arr , N , X , Y , Q ) ; } }