Remove array elements to reduce frequency of each array element to at most K | Java program for the above approach ; Function to remove array elements such that frequency of each distinct array element is at most K ; Base Case ; Stores index of array element by removing the array element such that the frequency of array elements is at most K ; Traverse the array ; If j < k or arr [ i ] > arr [ j - k ] ; Update arr [ j ] ; Remove array elements ; Function to print the array ; Traverse the array ; Utility Function to remove array elements such that frequency of each distinct array element is at most K ; Print updated array ; Driver Code
import java . util . * ; class GFG { static int [ ] RemoveElemArr ( int [ ] arr , int n , int k ) { if ( n == 0 n == 1 ) return arr ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( j < k arr [ i ] > arr [ j - k ] ) { arr [ j ++ ] = arr [ i ] ; } } while ( arr . length > j ) { arr = Arrays . copyOfRange ( arr , 0 , arr . length - 1 ) ; } return arr ; } static void printArray ( int [ ] arr ) { for ( int i = 0 ; i < arr . length ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void UtilRemov ( int [ ] arr , int n , int k ) { arr = RemoveElemArr ( arr , n , k ) ; printArray ( arr ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 } ; int k = 2 ; int n = arr . length ; UtilRemov ( arr , n , k ) ; } }