Minimum replacements required to make sum of all K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinOperations ( int arr [ ] , int N , int K ) { int operations = 0 ; for ( int i = 0 ; i < K ; i ++ ) { unordered_map < int , int > freq ; for ( int j = i ; j < N ; j += K ) freq [ arr [ j ] ] ++ ; int max1 = 0 , num ; for ( auto x : freq ) { if ( x . second > max1 ) { max1 = x . second ; num = x . first ; } } for ( auto x : freq ) { if ( x . first != num ) operations += x . second ; } } cout << operations ; } int main ( ) { int arr [ ] = { 3 , 4 , 3 , 5 , 6 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinOperations ( arr , N , K ) ; return 0 ; }