Array sum after replacing all occurrences of X by Y for Q queries | Java 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
import java . util . * ; class GFG { public static void sumOfTheArrayForQuery ( int [ ] A , int N , int [ ] X , int [ ] Y , int Q ) { int sum = 0 ; HashMap < Integer , Integer > count = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( count . containsKey ( A [ i ] ) ) { count . replace ( A [ i ] , count . get ( A [ i ] ) + 1 ) ; } else { count . put ( A [ i ] , 1 ) ; } } for ( int i = 0 ; i < Q ; i ++ ) { int x = X [ i ] , y = Y [ i ] ; if ( count . containsKey ( X [ i ] ) ) { sum -= count . get ( X [ i ] ) * X [ i ] ; sum += count . get ( X [ i ] ) * Y [ i ] ; } if ( count . containsKey ( Y [ i ] ) && count . containsKey ( X [ i ] ) ) { count . replace ( Y [ i ] , count . get ( Y [ i ] ) + count . get ( X [ i ] ) ) ; } if ( count . containsKey ( X [ i ] ) ) { count . replace ( X [ i ] , 0 ) ; } System . out . print ( 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 ) ; } }