MrainW's Home

All things come to those who wait!

0%

LeetCode 621. Task Scheduler

Question

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.

Return the least number of units of times that the CPU will take to finish all the given tasks.

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

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {

public int leastInterval(char[] tasks, int n) {
int[] record = new int[26];
for(char a : tasks){
record[a-'A']++;
}
Arrays.sort(record);
int max_n = record[25]-1;
int space = max_n* n;

for(int i = 24; i >=0&& record[i]>0; i--){
space -= Math.min(max_n,record[i]);
}
return space>0?tasks.length+space:tasks.length;

}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels