Make all array elements equal to K by repeatedly incrementing subsequences | Java 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
import java . io . * ; import java . util . * ; class GFG { static void minOperations ( int arr [ ] , int n , int k ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int ans = 0 ; while ( mp . containsKey ( k ) == false || mp . get ( k ) < n ) { for ( int i = 1 ; i <= k - 1 ; i ++ ) { if ( mp . containsKey ( i ) && mp . get ( i ) > 0 ) { mp . put ( i , mp . get ( i ) - 1 ) ; if ( mp . containsKey ( i + 1 ) ) mp . put ( i + 1 , mp . get ( i + 1 ) + 1 ) ; else mp . put ( i + 1 , 1 ) ; if ( mp . containsKey ( i + 1 ) && mp . get ( i + 1 ) == 1 ) { i ++ ; } } } ans ++ ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 3 , 4 } ; int K = 5 ; int N = arr . length ; minOperations ( arr , N , K ) ; } }