Check if the sum of K least and most frequent array elements are equal or not | 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
function checkSum ( arr , n , k ) { let m = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( m . has ( arr [ i ] ) ) { m . set ( m . get ( arr [ i ] ) , m . get ( arr [ i ] ) + 1 ) } else { m . set ( arr [ i ] , 1 ) ; } } let freq = new Array ( n + 1 ) ; for ( let i = 0 ; i < n ; i ++ ) { let f = m . get ( arr [ i ] ) ; if ( f != - 1 ) { freq [ f ] = new Array ( ) ; freq [ f ] . push ( arr [ i ] ) ; m . set ( arr [ i ] , - 1 ) ; } } let count = 0 ; let kleastfreqsum = 0 ; for ( let i = 0 ; i <= n ; i ++ ) { for ( let x in freq [ i ] ) { kleastfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } count = 0 ; let kmostfreqsum = 0 ; for ( let i = n ; i >= 0 ; i -- ) { for ( let x in freq [ i ] ) { kmostfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } if ( kleastfreqsum == kmostfreqsum ) return " " ; return " " ; } let arr = [ 3 , 2 , 1 , 2 , 3 , 3 , 4 ] ; let N = arr . length ; let K = 2 ; document . write ( checkSum ( arr , N , K ) ) ;