Task Scheduler

Jin Shang bio photo By Jin Shang

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example:

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].

Solution: priority queue

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        priority_queue<pair<int,int>> pq;
        map<char,int> cnt;
        for(char& c : tasks){
            cnt[c]++;
        }
        for(auto& p:cnt){
            pq.push(make_pair(p.second, p.first));
        }
        int ans = 0;
        int done = 0;
        while(!pq.empty()){
            vector<pair<int,int>> temp;
            for(int i =0;i<=n;i++){
                if(pq.empty()){
                    if(done == tasks.size()) return ans;
                    ans++;
                    continue;
                }
                temp.push_back(pq.top());
                pq.pop();
                done++;
                ans++;
            }
            for(auto& p:temp){
                p.first--;
                // cout<<p.second<<" ";
                if(p.first>0)pq.push(p);
            }
        }
        return ans;
    }
};

Solution: slot allocation

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        vector<int> mp(26, 0);
        for (char c : tasks)
            ++mp[c - 'A'];
        sort(mp.begin(), mp.end());
        int max_num = mp[25] - 1;
        int idle = max_num * n;
        for (int i = 24; i >= 0 && mp[i] > 0; --i)
            idle -= min(mp[i], max_num);
        return idle > 0 ? idle + tasks.size() : tasks.size();
    }
};