Largest element in the array that is repeated exactly k times | Java 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
import java . util . HashMap ; import java . util . Map ; class GfG { static void solve ( int arr [ ] , int n , int k ) { HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! m . containsKey ( arr [ i ] ) ) m . put ( arr [ i ] , 0 ) ; m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } int max = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . get ( arr [ i ] ) == k && max == Integer . MIN_VALUE ) { max = arr [ i ] ; } else if ( m . get ( arr [ i ] ) == k && max < arr [ i ] ) { max = arr [ i ] ; } } if ( max == Integer . MIN_VALUE ) System . out . println ( " No ▁ such ▁ element " ) ; else System . out . println ( max ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 } ; int k = 4 ; int n = arr . length ; solve ( arr , n , k ) ; } }