Task schedule 

https://leetcode.com/problems/task-scheduler/solution/

https:///tongzhang1994/Facebook-Interview-Coding/blob/master/Task%20schedule%20with%20cool%20down%20time.java

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 1:

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









Approach #1 Using Sorting

public class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] map = new int[26];
        for (char c: tasks)
            map[c - 'A']++;
        Arrays.sort(map);
        int time = 0;
        while (map[25] > 0) {
            int i = 0;
            while (i <= n) {
                if (map[25] == 0)
                    break;
                if (i < 26 && map[25 - i] > 0)
                    map[25 - i]--;
                time++;
                i++;
            }
            Arrays.sort(map);
        }
        return time;
    }
}
class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] map = new int[26];
        for (char c: tasks)
            map[c - 'A']++;
        PriorityQueue < Integer > queue = new PriorityQueue < > (26, Collections.reverseOrder());
        for (int f: map) {
            if (f > 0)
                queue.add(f);
        }
        int time = 0;
        while (!queue.isEmpty()) {
            int i = 0;
            List < Integer > temp = new ArrayList < > ();
            while (i <= n) {
                if (!queue.isEmpty()) {
                    if (queue.peek() > 1)
                        temp.add(queue.poll() - 1);
                    else
                        queue.poll();
                }
                time++;
                i++;
                if (queue.isEmpty() && temp.size() == 0)
                    break;
                
            }
            for (int l: temp)
                queue.add(l);
        }
        return time;
    }
}

 

================================



顺序已经规定好了的task schedule:输出的是最后的时间

thread: 1, 2, 1, 1, 3, 4; 冷却时间: 2 time slot,scheduler应该是这样的:1, 2, _, 1, _, _, 1, 3, 4,最后返回9.


private static int taskSchedule1(int[] tasks, int cooldown) {
    if (tasks == null || tasks.length == 0)    return 0;
    HashMap<Integer, Integer> map = new HashMap<>();
    int slots = 0;
    for (int task : tasks) {
        //if we need to wait for the cooldown of the same task, just update the slots
        if (map.containsKey(task) && map.get(task) > slots) 
            slots = map.get(task);
        }
        //update the time slot to the time when curr task can be done again
        map.put(task, slots + 1 + cooldown); 
        slots++; //important!! update the used 1 slot of curr task
    }
    return slots;
}













顺序已经规定好了的task schedule:输出的是字符串 '_'

//if we need to output a string of the task scheduling(without reordering), eg.1,2,1,1,3,4, k=2, -> 12_1__134

public String taskSchedule2(int[] tasks, int cooldown) {
   if (tasks == null || tasks.length == 0)   return "";
   Map<Integer, Integer> map = new HashMap<>();//store indices, where cooldown stops, of tasks in window
   int slots = 0;
   StringBuilder sb = new StringBuilder();
   for (int task : tasks) {
       if (map.containsKey(task) && map.get(task) > slots) {
           int waitingTime = map.get(task) - slots;
           while (waitingTime-- > 0) 
               sb.append("_");
           slots = map.get(task);
       }
       map.put(task, slots + cooldown + 1);
       sb.append(task);
       slots++;
   }
   return sb.toString();
}
      
      

 

621. Task Scheduler 
https:///watch?v=YCD_iYxyXoo&t=649s

https:///tongzhang1994/Facebook-Interview-Coding/blob/master/Task%20schedule%20with%20cool%20down%20time.java

Greedy:      return Math.max(result, tasks.length); ///// idk why 

max((n+1) * (k -1) + p,  total number of tasks)

N is the cool down time 
K is the highest freq 
P is the number of tasks with the same freq as the highest freq 





Case 1 : we need idle time : number of time we need is (n+1) * (k -1) + p
Case 2 : we don’t need idle time to still be able to satisfy” the there must be at least n intervals that CPU are doing different tasks or just be idle.” The all the tasks can be combined in a way that no idle time needed 




======
task scheduler一个经典的followup就是 如果tasks很多很多  但是cooldown time很小 如何优化空间复杂度到 O(cooldown time)注意这里顺序是不能变的
. visit 1point3acres for more.
刚才有美国同学面了phone说面试官问这个followup他没答上来!!后来我想了想发现。。我也不会lul 搜了下地里没看到靠谱的代码啊

请教!
面试官给的提示是用queue
同学面的第二个题是merge two arrays of intervals 面经题地里有~. fro



3,无序的,频率统计的做法,算最后时间

class Solution {
    public int leastInterval(char[] tasks, int n) {
      if(n == 0){
          return tasks.length;
      }
      int m = Integer.MIN_VALUE;
      HashMap<Character, Integer> map = new HashMap<>();
      for(Character c : tasks){
        if(!map.containsKey(c)){
          map.put(c, 1);
          m = Math.max(1, m);
        }else{
          int count = map.get(c);
          map.put(c, count + 1);
          m = Math.max(count + 1, m);
        }
      }
      
      int same = 0;
      for(Character c: map.keySet()){     // for (int frequency : map.values()) 
        if(map.get(c) == m){
          same++;
        }
      }


      
      int result = (m - 1) * (n + 1) + same;
      
      return Math.max(result, tasks.length); ///// idk why 
    }
}
复制代码
 Task schedule with cool down time. 给的任务不能打乱顺序执行,同样的任务如果在cooldown里面则加idle。要求给出所有任务执行的结果////顺序不变  tongzhang1994

 

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 1:

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

Note:

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