Task Scheduler

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
Find the minimum CPU units to do all tasks

Example:

Input:  tasks={'A','A','A','B','B','B'}, n=2
Output: 8

Approach

Java


import java.util.Arrays;
public class TaskScheduler {
    public static void main(String[] args) {
        char tasks[] = { 'A''A''A''B''B''B' };
        int n = 2;
        System.out.println(leastInterval(tasks, n));
    }

    static int leastInterval(char[] tasksint n) {
        int m = tasks.length;
        if (n == 0)
            return m;
        if (m == 0)
            return 0;
        int f[] = new int[26];
        for (int i = 0; i < m; i++)
            f[tasks[i] - 'A']++;

        Arrays.sort(f);

        int i = 25;
        while (i > 0 && f[i] == f[25])
            i--;
        return Math.max(m, (f[25] - 1) * (n + 1) + (25 - i));
    }
    
}

C++

#include <bits/stdc++.h>
using namespace std;


int leastInterval(vector<char>& tasksint n)
{
        int m=tasks.size();
        if(n==0)
               return m;
        if(m==0)
               return 0;
        vector<intf(26,0);
        for(int i=0;i<m;i++)
                f[tasks[i]-'A']++;
        sort(f.begin(),f.end(),greater<int>());
        int i=0;
        while(i<26&&f[i]==f[0])
               i++;
        return max(m,(f[0]-1)*(n+1)+i);
}
int main()
{
    vector<char>tasks ={'A','A','A','B','B','B'};
    int  n = 2;
    cout<<leastInterval(tasks,n);
    return 0;
}


No comments:

Post a Comment