Minimum replacements required to make sum of all K | Java program for the above approach ; Function to find minimum number of operations required to make sum of all subarrays of size K equal ; Stores number of operations ; Iterate in the range [ 0 , K - 1 ] ; Stores frequency of elements separated by distance K ; Stores maximum frequency and corresponding element ; Find max frequency element and its frequency ; Update the number of operations ; Print the result ; Driver code ; Given Input ; Function Call
import java . lang . * ; import java . util . * ; class GFG { static void findMinOperations ( int arr [ ] , int N , int K ) { int operations = 0 ; for ( int i = 0 ; i < K ; i ++ ) { Map < Integer , Integer > freq = new HashMap < > ( ) ; for ( int j = i ; j < N ; j += K ) freq . put ( arr [ j ] , freq . getOrDefault ( arr [ j ] , 0 ) + 1 ) ; int max1 = 0 , num = - 1 ; for ( Map . Entry < Integer , Integer > x : freq . entrySet ( ) ) { if ( x . getValue ( ) > max1 ) { max1 = x . getValue ( ) ; num = x . getKey ( ) ; } } for ( Map . Entry < Integer , Integer > x : freq . entrySet ( ) ) { if ( x . getKey ( ) != num ) operations += x . getValue ( ) ; } } System . out . print ( operations ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 4 , 3 , 5 , 6 } ; int K = 2 ; int N = arr . length ; findMinOperations ( arr , N , K ) ; } }