Minimum time required to complete all tasks without altering their order
Given 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 the given order such that each task takes one unit of time and each task of the same type must be performed at an interval of K units.
Input: S = “ABACCA”, K = 2
Below are the order of task that is to be completed:
A → B → _ → A → C → _ → _ → C → A.
Therefore, the total time required is 9 units.
Input: S = “AAAA”, K = 3
Approach: The given problem can be solved by Hashing by keeping track of the last instant of each task and find the overall minimum time accordingly. Follow the steps below to solve the problem:
- Initialize a hashmap, say M, to keep track of the last time instant of each task.
- Initialize a variable, say ans as 0, to store the resultant minimum time.
- Traverse the given string S and perform the following steps:
- If the character S[i] is present in M, then store the last instant of S[i] in a variable, say t.
- If the value of (ans – t) is at most K, then add the value of K – (ans – t) + 1 to variable ans.
- Update the last time instant of the character S[i] in M to ans, and increment the value of ans by 1.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Please Login to comment...