Tuesday, 26 Oct 2021

# Minimum time required to complete all tasks with alteration of their order allowed

Minimum time required to complete all tasks with alteration of their order allowedGiven a string S consisting of N characters (representing the tasks to perform) and a positive integer K, the task is to find the minimum time required to complete all the given tasks in any order, given that each task takes one unit of time and each task of the same type must be performed at an interval of K units.Examples:Input: S = “AAABBB”, K = 2Output: 8Explanation:Below are the order of task that is to be completed:A → B → _ → A → B → _ → A → B Therefore, the total time required is 8 units.Input: S = “AAABBB”, K = 0Output: 6Approach: The given problem can be solved based on the following observations:To complete the tasks in minimum time, the idea is to find the maximum occurring character in the array and complete those tasks first.Let the maximum occurring character be X and its frequency be freq.Now, to complete tasks of type X first, there must be difference of K between them, which leaves a total number of (freq – 1) * K empty slots in between the tasks of X.Then, fill these empty slots by traversing the other tasks since the other tasks have frequency less than or equal to that of X.Follow the steps below to solve the problem:Initialize a HashMap, say M, that stores the frequency of each character in the given string S.Initialize two variables, maxchar and maxfreq, that stores the maximum occurring character and its frequency respectively.Traverse the given string S and increment the frequency of S[i] in the map M and if it is greater than maxfreq,   and update the value of maxchar to S[i] and the value of maxfreq to its frequency.Store the number of empty slots in a variable, say S, as (maxfreq – 1) * K.Traverse the HashMap, M and for every character other than maxchar, update the value of empty slots, S by subtracting minimum of (maxfreq – 1) and M[S[i]] from S.Store the required minimum time in a variable, ans as sum of N and S, if the value of S ≥ 0.After completing the above steps, print the value of ans as the result.Below is the implementation of the above approach:C++  #include using namespace std;  void findMinimumTime(string& S, int N,                     int K){        if (N == 0) {        cout maxfreq) {            maxfreq = um[S[i]];            maxchar = S[i];        }    }          int emptySlots = (maxfreq – 1) * K;          for (auto& it : um) {          if (it.first == maxchar)            continue;                  emptySlots -= min(it.second,                          maxfreq – 1);    }          int ans = N + max(0, emptySlots);          cout