1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
unordered_map<char, int> freq;
for (const char& c : tasks) {
++ freq[c];
}
int m = freq.size();
vector<int> nextValid, rest;
for (auto [_, v]: freq) {
nextValid.push_back(1);
rest.push_back(v);
}
int time = 0;
for (int i = 0; i < tasks.size(); ++ i) {
++ time;
int minNextValid = INT_MAX;
for (int j = 0; j < m; j ++) {
if (rest[j]) {
minNextValid = min(minNextValid, nextValid[j]);
}
}
time = max(time, minNextValid);
int best = -1;
for (int j = 0; j < m; j ++) {
if (rest[j] && nextValid[j] <= time) {
if (best == -1 | rest[j] > rest[best]) {
best = j;
}
}
}
nextValid[best] = time + n + 1;
-- rest[best];
}
return time;
}
};
|