Find sum of product of every number and its frequency in given range | C # 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
using System ; using System . Collections . Generic ; class GFG { public static void answerQueries ( int [ ] arr , int n , int [ , ] queries ) { for ( int i = 0 ; i < queries . GetLength ( 0 ) ; i ++ ) { int ans = 0 ; int l = queries [ i , 0 ] - 1 ; int r = queries [ i , 1 ] - 1 ; Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; for ( int j = l ; j < r + 1 ; j ++ ) { freq [ arr [ j ] ] = freq . GetValueOrDefault ( arr [ j ] , 0 ) + 1 ; } foreach ( int k in freq . Keys ) { ans += k * freq [ k ] ; } Console . WriteLine ( ans ) ; } } static public void Main ( ) { int [ ] arr = { 1 , 2 , 1 } ; int n = arr . Length ; int [ , ] queries = { { 1 , 2 } , { 1 , 3 } } ; answerQueries ( arr , n , queries ) ; } }