-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask-scheduler.cpp
46 lines (38 loc) · 945 Bytes
/
task-scheduler.cpp
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
41
42
43
44
45
46
/*
* Copyright (c) 2021, Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
// name: task-scheduler
// url: https://leetcode.com/problems/task-scheduler
// difficulty: 2
class Solution {
public:
int leastInterval(vector<char> &tasks, int n) {
if (0 == n) {
return tasks.size();
}
unordered_map<char, int> hist;
int peak = 0;
// create a histogram of task frequencies, also keep track of peak frequency
for (const auto &task : tasks) {
hist[task]++;
peak = max(peak, hist[task]);
}
if (hist.size() == tasks.size()) {
return tasks.size();
}
// find the number of tasks that share the peak frequency
int npeak = 0;
for (auto &kv : hist) {
if (kv.second == peak) {
++npeak;
}
}
return max(int(tasks.size()), (peak - 1) * (n + 1) + npeak);
}
};