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
def checkSum ( arr , n , k ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in m : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT freq = [ [ ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT f = m [ arr [ i ] ] NEW_LINE if ( f != - 1 ) : NEW_LINE INDENT freq [ f ] . append ( arr [ i ] ) NEW_LINE m [ arr [ i ] ] = - 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE kleastfreqsum = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for x in freq [ i ] : NEW_LINE INDENT kleastfreqsum += x NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT count = 0 NEW_LINE kmostfreqsum = 0 NEW_LINE i = n NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT for x in freq [ i ] : NEW_LINE INDENT kmostfreqsum += x NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( kleastfreqsum == kmostfreqsum ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 2 , 3 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( checkSum ( arr , N , K ) ) NEW_LINE DEDENT