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
using System ; using System . Collections . Generic ; public class GFG { static void minOperations ( int [ ] arr , int n , int k ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 ; } else { mp . Add ( arr [ i ] , 1 ) ; } } int ans = 0 ; while ( mp . ContainsKey ( k ) == false mp [ k ] < n ) { for ( int i = 1 ; i <= k - 1 ; i ++ ) { if ( mp . ContainsKey ( i ) && mp [ i ] > 0 ) { mp [ i ] = mp [ i ] - 1 ; if ( mp . ContainsKey ( i + 1 ) ) mp [ i + 1 ] = mp [ i + 1 ] + 1 ; else mp . Add ( i + 1 , 1 ) ; if ( mp . ContainsKey ( i + 1 ) && mp [ i + 1 ] == 1 ) { i ++ ; } } } ans ++ ; } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 3 , 4 } ; int K = 5 ; int N = arr . Length ; minOperations ( arr , N , K ) ; } }