Minimum time required to complete all tasks with alteration of their order allowed | Java program for the above approach ; Function to find the minimum time required to complete the tasks if the order of tasks can be changed ; If there is no task , print 0 ; Store the maximum occurring character and its frequency ; Stores the frequency of each character ; Traverse the string S ; Increment the frequency of the current character ; Update maxfreq and maxchar ; Store the number of empty slots ; Traverse the hashmap , um ; Fill the empty slots ; Store the required result ; Print the result ; Driver code
import java . util . HashMap ; import java . util . Map ; class GFG { static void findMinimumTime ( String S , int N , int K ) { if ( N == 0 ) { System . out . println ( 0 ) ; return ; } int maxfreq = Integer . MIN_VALUE ; char maxchar = ' ▁ ' ; HashMap < Character , Integer > um = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { um . put ( S . charAt ( i ) , um . getOrDefault ( S . charAt ( i ) , 0 ) + 1 ) ; if ( um . get ( S . charAt ( i ) ) > maxfreq ) { maxfreq = um . get ( S . charAt ( i ) ) ; maxchar = S . charAt ( i ) ; } } int emptySlots = ( maxfreq - 1 ) * K ; for ( Map . Entry < Character , Integer > it : um . entrySet ( ) ) { if ( it . getKey ( ) == maxchar ) continue ; emptySlots -= Math . min ( it . getValue ( ) , maxfreq - 1 ) ; } int ans = N + Math . max ( 0 , emptySlots ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " AAABBB " ; int K = 2 ; int N = S . length ( ) ; findMinimumTime ( S , N , K ) ; } }