Skip to content

Commit e1d2c9b

Browse files
committed
🚀 29-Jul-2020
1 parent d750a94 commit e1d2c9b

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
2+
3+
However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
4+
5+
You need to return the least number of units of times that the CPU will take to finish all the given tasks.
6+
7+
8+
9+
Example 1:
10+
11+
Input: tasks = ["A","A","A","B","B","B"], n = 2
12+
Output: 8
13+
Explanation:
14+
A -> B -> idle -> A -> B -> idle -> A -> B
15+
There is at least 2 units of time between any two same tasks.
16+
Example 2:
17+
18+
Input: tasks = ["A","A","A","B","B","B"], n = 0
19+
Output: 6
20+
Explanation: On this case any permutation of size 6 would work since n = 0.
21+
["A","A","A","B","B","B"]
22+
["A","B","A","B","A","B"]
23+
["B","B","B","A","A","A"]
24+
...
25+
And so on.
26+
Example 3:
27+
28+
Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
29+
Output: 16
30+
Explanation:
31+
One possible solution is
32+
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A
33+
34+
35+
Constraints:
36+
37+
The number of tasks is in the range [1, 10000].
38+
The integer n is in the range [0, 100].
39+
40+
41+
42+
43+
44+
45+
46+
47+
48+
49+
50+
class Solution {
51+
public:
52+
int leastInterval(vector<char>& tasks, int n) {
53+
if(n==0) return (int)tasks.size();
54+
map<char,int> freq;
55+
int max_freq = 0,inc=0;
56+
for(int x : tasks) {freq[x]++; max_freq = max(max_freq, freq[x]);}
57+
int idle_time = (max_freq-1)*(n+1)+1;
58+
for(auto it: freq){
59+
if(it.second==max_freq) inc++;
60+
}
61+
int ans = idle_time+(inc-1);
62+
return max(ans, (int)tasks.size());
63+
}
64+
};

0 commit comments

Comments
 (0)