Find sum of product of every number and its frequency in given range | Java program to find sum of product of every number and square of its frequency in the given range ; Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; Hashmap for storing frequency ; Incrementing the frequency ; Adding the contribution of ith number ; Print answer ; Driver code ; Calling function
import java . util . * ; class GFG { public static void answerQueries ( int [ ] arr , int n , int [ ] [ ] queries ) { for ( int i = 0 ; i < queries . length ; i ++ ) { int ans = 0 ; int l = queries [ i ] [ 0 ] - 1 ; int r = queries [ i ] [ 1 ] - 1 ; Map < Integer , Integer > freq = new HashMap < > ( ) ; for ( int j = l ; j < r + 1 ; j ++ ) { freq . put ( arr [ j ] , freq . getOrDefault ( arr [ j ] , 0 ) + 1 ) ; } for ( int k : freq . keySet ( ) ) { ans += k * freq . get ( k ) ; } System . out . println ( ans ) ; } } public static void main ( String args [ ] ) { int [ ] arr = { 1 , 2 , 1 } ; int n = arr . length ; int [ ] [ ] queries = { { 1 , 2 } , { 1 , 3 } } ; answerQueries ( arr , n , queries ) ; } }