Skip to content

Commit 8cf16ca

Browse files
committed
applying a greedy approach by sorting the count array
1 parent 4f2ec37 commit 8cf16ca

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

greedy/leastInterval.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public int leastInterval(char[] tasks, int n) {
3+
/*
4+
We follow a greedy approach by sorting the char count table
5+
after we have done a task and completed the cooling period.
6+
Number of iterations will be equal to resultant time O(time).
7+
*/
8+
int[] map = new int[26]
9+
10+
for (int i=0; i<tasks.length; i++){
11+
map[tasks.charAt(i) - 'A']++;
12+
}
13+
14+
Arrays.sort(map);
15+
int time = 0;
16+
17+
while(map[25] > 0) {
18+
int i=0;
19+
while(i <= n) {
20+
if (i < 26 && map[25-i] > 0) {
21+
map[25-i]--;
22+
}
23+
i++;
24+
time++;
25+
}
26+
Arrays.sort(map);
27+
}
28+
29+
return time;
30+
31+
}
32+
}

0 commit comments

Comments
 (0)