
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Task Scheduler in C++
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(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; 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; } }; main(){ vector<char> v = {'A','A','A','B','B','B'}; Solution ob; cout << (ob.leastInterval(v, 2)) ; }
Input
{'A','A','A','B','B','B'} 2
Output
8