public class Solution {

public int leastInterval(char[] tasks, int n) {

if (n == 0) {

return tasks.length;

}

int[] counter = new int[26];

for (char c: tasks) {

counter[c - 'A']++;

}

```
Arrays.sort(counter);
int res = 0;
while ((25 - n) >= 0 && counter[25 - n] != 0) {
res += n + 1;
for (int j = 25; j >= 25 - n; j--) {
if (counter[j] == 0)
break;
counter[j]--;
}
Arrays.sort(counter);
}
if (counter[25] == 0)
return res;
res += (counter[25] - 1) * (n + 1);
for (int i = 25; i>=0; i--) {
if (counter[i] == counter[25]) {
res += 1;
}
}
return res;
}
```

}