Task Scheduler n C++

C++Server Side ProgrammingProgramming

Suppose we have a char array representing tasks CPU need to do. This contains uppercase letters A to Z where different letters represent different tasks. The tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one job or just be idle. However, there is a non-negative cooling interval called n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. We have to find the least number of intervals the CPU will take to finish all the given tasks. So if the input is [A, A, A, B, B, B] and n is 2, then the output will be 8, as A → B → idle → A → B → idle → A → B

To solve this, we will follow these steps −

  • Create a map m, and store the frequency of all characters stored in the task array

  • Define priority queue pq

  • for each key-value pair present at m, insert frequency values into pq

  • ans := 0, cycle := n + 1

  • while pq is not empty

    • define array temp, set time := 0

    • for i in range 0 and pq is not empty, and i − cycle

      • insert top element of pq into temp, delete top from pq, increase temp by 1

    • for i in range 0 to size of temp

      • decrease temp[i] by 1

      • if temp[i] is not 0, then insert temp[i] into pq

    • ans := ans + time when pq is empty, otherwise cycle

  • return ans

Example

Let us see the following implementation to get better understanding −

class Solution {
   public:
   int leastInterval(vector<char>& t, int n) {
      map <char,int> m;
      for(int i =0;i<t.size();i++){
         m[t[i]]++;
      }
      map <char, int> :: iterator i = m.begin();
      priority_queue <int> pq;
      while(i != m.end()){
         pq.push(i->second);
         i++;
      }
      int ans = 0;
      int cycle = n + 1;
      while(!pq.empty()){
         vector <int> temp;
         int time = 0;
         for(int i = 0; !pq.empty() && i < cycle; i++){
            temp.push_back(pq.top());
            pq.pop();
            time++;
         }
         for(int i = 0;i < temp.size(); i++){
            temp[i]-- ;
            if(temp[i])pq.push(temp[i]);
         }
         ans += pq.empty()? time : cycle;
      }
      return ans;
   }
};

Input

[[1,1],2,[1,1]]

Output

[1,1,2,1,1]
raja
Published on 17-Mar-2020 06:20:38
Advertisements