Make all array elements equal to K by repeatedly incrementing subsequences | C ++ program for the above approach ; Function to find the minimum number of operations required to make all elements equal to k ; Initialize a hashmap ; Store frequency of array elements ; Store the minimum number of operations required ; Iterate until all array elements becomes equal to K ; Iterate through range [ 1 , k - 1 ] since only one element can be increased from each group ; Check if the current number has frequency > 0 , i . e . , it is a part of a group ; If true , decrease the frequency of current group of element by 1 ; Increase the frequency of the next group of elements by 1 ; If the next element is not the part of any group , then skip it ; Increment count of operations ; Print the count of operations ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( int arr [ ] , int n , int k ) { map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] ++ ; } int ans = 0 ; while ( mp [ k ] < n ) { for ( int i = 1 ; i <= k - 1 ; i ++ ) { if ( mp [ i ] ) { mp [ i ] -- ; mp [ i + 1 ] ++ ; if ( mp [ i + 1 ] == 1 ) { i ++ ; } } } ans ++ ; } cout << ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 4 } ; int K = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minOperations ( arr , N , K ) ; return 0 ; }