No sorting solution.

I found the explanation given here is too wordy: https://leetcode.com/articles/task-scheduler/

tasks = ["A","A","A","B","B","B"], n = 2

The solution will be:

A,B,#
A,B,#
A,B

So you only need to count number of #.

You only need to consider row 1 and row 2. That's why we let max-- and Math.min(max, t) in the code.

The reason of writing n + 1 is that if n is 2, actually means we need 3 columns.

Row 1 and 2 has 2 * 3 totally spaces, then we deduct 2 A and 2B, then we still have two space.

At the end, we check is space smaller than 0, it means cool time is short, and we have more tasks, then every task has enough time to cool down, so the length is exactly the length of tasks.

Otherwise, we let the length of tasks plus the number of #

public int leastInterval(char[] tasks, int n) {
int[] times = new int[26];
for(char t: tasks){
times[t - 'A']++;
}
int max = 0;
for(int t: times){
max = Math.max(max, t);
}
max--;
System.out.println(max);
int space = max * (n + 1);
for(int t: times){
space -= Math.min(max, t);
}
if(space <= 0){
return tasks.length;
} else {
return tasks.length + space;
}
}