Check if the sum of K least and most frequent array elements are equal or not | C # program for the above approach ; Function to compare the sum of K most and least occurrences ; Stores frequency of array element ; Stores the frequencies as indexes and putelements with the frequency in a vector ; Find the frequency ; Insert in the vector ; Stores the count of elements ; Traverse the frequency array ; Find the kleastfreqsum ; If the count is K , break ; Reinitialize the count to zero ; Traverse the frequency ; Find the kmostfreqsum ; If the count is K , break ; Comparing the sum ; Otherwise , return No ; Driver Code
using System ; using System . Collections . Generic ; public class GFG { static String checkSum ( int [ ] arr , int n , int k ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( m . ContainsKey ( arr [ i ] ) ) { m [ arr [ i ] ] = m [ arr [ i ] ] + 1 ; } else { m . Add ( arr [ i ] , 1 ) ; } List < int > [ ] freq = new List < int > [ n + 1 ] ; for ( int i = 0 ; i < freq . Length ; i ++ ) freq [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int f = m [ arr [ i ] ] ; if ( f != - 1 ) { freq [ f ] . Add ( arr [ i ] ) ; if ( m . ContainsKey ( arr [ i ] ) ) { m [ arr [ i ] ] = - 1 ; } else { m . Add ( arr [ i ] , - 1 ) ; } } } int count = 0 ; int kleastfreqsum = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { foreach ( int x in freq [ i ] ) { kleastfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } count = 0 ; int kmostfreqsum = 0 ; for ( int i = n ; i >= 0 ; i -- ) { foreach ( int x in freq [ i ] ) { kmostfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } if ( kleastfreqsum == kmostfreqsum ) return " Yes " ; return " No " ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 , 2 , 3 , 3 , 4 } ; int N = arr . Length ; int K = 2 ; Console . Write ( checkSum ( arr , N , K ) ) ; } }