publicclassSolution {publicstaticinttaskSchedule(int[] tasks,int cooldown) {if (tasks ==null||tasks.length==0) {return0; }HashMap<Integer,Integer> map =newHashMap<>();int slots =0;for (int task : tasks) {// if task is already used or need to waitif (map.containsKey(task) &&map.get(task) > slots) { slots =map.get(task); }map.put(task, slots + cooldown +1); // next available slot for task slots++; // used 1 slot for current task }return slots; }}
Follow Up
Find the task that appears for the most time. Use a map to count the number of the times the task appears then get the maximum count.The result is decided by the maximum count and the number of tasks with maximum count
Two conditions:
(1) 5 4 _ _ _ 5 4 _ _ _ 5 4 _ _ _ 5 4 the rest tasks cannot fill the empty slots
5 4 3 2 _ 5 4 3 2 _ 5 4 _ _ _ 5 4
the answer is (maxCount - 1) * (interval + 1) + CountOfMax
(2) 5 4 _ _ _ 5 4 _ _ _ 5 4 _ _ _ 5 4 the rest tasks cannot fill the empty slots
5 4 3 2 1 6 5 4 3 2 1 6 5 4 6 _ _ 5 4
the answer is the length of the nums
the task which does not have max count first fills the empty slots and then just insert any valid place