Largest element in the array that is repeated exactly k times | C ++ implementation of above approach ; Function that finds the largest element that occurs exactly ' k ' times ; store the frequency of each element ; to store the maximum element ; if current element has frequency ' k ' and current maximum hasn 't been set ; set the current maximum ; if current element has frequency ' k ' and it is greater than the current maximum ; change the current maximum ; if there is no element with frequency ' k ' ; print the largest element with frequency ' k ' ; Driver code ; find the largest element that is repeated K times
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int arr [ ] , int n , int k ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) { m [ arr [ i ] ] ++ ; } int max = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ arr [ i ] ] == k && max == INT_MIN ) { max = arr [ i ] ; } else if ( m [ arr [ i ] ] == k && max < arr [ i ] ) { max = arr [ i ] ; } } if ( max == INT_MIN ) cout << " No ▁ such ▁ element " << endl ; else cout << max << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( int ) ; solve ( arr , n , k ) ; return 0 ; }