Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 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 = 2
Output: 8
Explanation:
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 = 0
Output: 6

Approach: 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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum time
// required to complete the tasks if
// the order of tasks can be changed
void findMinimumTime(string& S, int N,
                     int K)
{
    // If there is no task, print 0
    if (N == 0) {
        cout << 0;
        return;
    }
 
    // Store the maximum occurring
    // character and its frequency
    int maxfreq = INT_MIN;
    char maxchar;
 
    // Stores the frequency of each
    // character
    unordered_map<char, int> um;
 
    // Traverse the string S
    for (int i = 0; i < N; i++) {
 
        // Increment the frequency of
        // the current character
        um[S[i]]++;
 
        // Update maxfreq and maxchar
        if (um[S[i]] > maxfreq) {
            maxfreq = um[S[i]];
            maxchar = S[i];
        }
    }
 
    // Store the number of empty slots
    int emptySlots = (maxfreq - 1) * K;
 
    // Traverse the hashmap, um
    for (auto& it : um) {
 
        if (it.first == maxchar)
            continue;
 
        // Fill the empty slots
        emptySlots -= min(it.second,
                          maxfreq - 1);
    }
 
    // Store the required result
    int ans = N + max(0, emptySlots);
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    string S = "AAABBB";
    int K = 2;
    int N = S.length();
    findMinimumTime(S, N, K);
 
    return 0;
}


Java




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


Python3




# Python3 program for the above approach
import sys
from collections import defaultdict
 
# Function to find the minimum time
# required to complete the tasks if
# the order of tasks can be changed
def findMinimumTime(S, N, K):
     
    # If there is no task, print 0
    if (N == 0):
        print(0)
        return
 
    # Store the maximum occurring
    # character and its frequency
    maxfreq = -sys.maxsize
 
    # Stores the frequency of each
    # character
    um = defaultdict(int)
 
    # Traverse the string S
    for i in range(N):
 
        # Increment the frequency of
        # the current character
        um[S[i]] += 1
 
        # Update maxfreq and maxchar
        if (um[S[i]] > maxfreq):
            maxfreq = um[S[i]]
            maxchar = S[i]
 
    # Store the number of empty slots
    emptySlots = (maxfreq - 1) * K
 
    # Traverse the hashmap, um
    for it in um:
        if (it == maxchar):
            continue
 
        # Fill the empty slots
        emptySlots -= min(um[it],
                          maxfreq - 1)
 
    # Store the required result
    ans = N + max(0, emptySlots)
 
    # Print the result
    print(ans)
 
# Driver Code
if __name__ == "__main__":
 
    S = "AAABBB"
    K = 2
    N = len(S)
     
    findMinimumTime(S, N, K)
     
# This code is contributed by ukasp


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum time
// required to complete the tasks if
// the order of tasks can be changed
static void findMinimumTime(string S, int N, int K)
{
     
    // If there is no task, print 0
    if (N == 0)
    {
        Console.Write(0);
        return;
    }
 
    // Store the maximum occurring
    // character and its frequency
    int maxfreq = Int32.MinValue;
    char maxchar = ' ';
 
    // Stores the frequency of each
    // character
    Dictionary<char,
               int> um = new Dictionary<char,
                                        int>();
 
    // Traverse the string S
    for(int i = 0; i < N; i++)
    {
         
        // Increment the frequency of
        // the current character
        if (um.ContainsKey(S[i]))
            um[S[i]]++;
        else
            um.Add(S[i], 1);
 
        // Update maxfreq and maxchar
        if (um.ContainsKey(S[i]) &&
            um[S[i]] > maxfreq)
        {
            maxfreq = um[S[i]];
            maxchar = S[i];
        }
    }
 
    // Store the number of empty slots
    int emptySlots = (maxfreq - 1) * K;
 
    // Traverse the hashmap, um
    foreach(KeyValuePair<char, int> kvp in um)
    {
 
        if (kvp.Key == maxchar)
            continue;
 
        // Fill the empty slots
        emptySlots -= Math.Min(kvp.Value,
                               maxfreq - 1);
    }
 
    // Store the required result
    int ans = N + Math.Max(0, emptySlots);
 
    // Print the result
    Console.Write(ans);
}
 
// Driver Code
public static void Main()
{
    string S = "AAABBB";
    int K = 2;
    int N = S.Length;
     
    findMinimumTime(S, N, K);
}
}
 
// This code is contributed by bgangwar59


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find the minimum time
// required to complete the tasks if
// the order of tasks can be changed
function findMinimumTime(s, N, K)
{
     
    // If there is no task, print 0
    if (N == 0)
    {
        document.write(0);
        return;
    }
 
    // Store the maximum occurring
    // character and its frequency
    let maxfreq = Number.MIN_SAFE_INTEGER;
    let maxchar;
 
    // Stores the frequency of each
    // character
    let um = new Map();
 
    // Traverse the string S
    for(let i = 0; i < N; i++)
    {
         
        // Increment the frequency of
        // the current character
        if (um.has(s[i]))
        {
           um.set(s[i], um.get(s[i]) + 1)
        }
        else
        {
            um.set(s[i], 1)
        }
 
        // Update maxfreq and maxchar
        if (um.get(S[i]) > maxfreq)
        {
            maxfreq = um.get(S[i]);
            maxchar = S[i];
        }
    }
 
    // Store the number of empty slots
    let emptySlots = (maxfreq - 1) * K;
 
    // Traverse the hashmap, um
    for(let it of um)
    {
        if (it[0] == maxchar)
            continue;
 
        // Fill the empty slots
        emptySlots -= Math.min(
            it[1], maxfreq - 1);
    }
 
    // Store the required result
    let ans = N + Math.max(0, emptySlots);
 
    // Print the result
    document.write(ans);
}
 
// Driver Code
let S = "AAABBB";
let K = 2;
let N = S.length;
 
findMinimumTime(S, N, K);
 
// This code is contributed by _saurabh_jaiswal.
 
</script>


Output: 

8

 

Time Complexity: O(N)
Auxiliary Space: O(256)



Last Updated : 15 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads