forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-amount-of-time-to-collect-garbage.cpp
50 lines (48 loc) · 1.39 KB
/
minimum-amount-of-time-to-collect-garbage.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
47
48
49
50
// Time: O(n * l), l = max(len(g) for g in garbage) = O(10)
// Space: O(1)
// simulation, prefix sum
class Solution {
public:
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
int result = 0;
unordered_map<char, int> lookup;
for (int i = 0; i < size(garbage); ++i) {
for (const auto& c : garbage[i]) {
lookup[c] = i;
}
if (i + 1 < size(travel)) {
travel[i + 1] += travel[i];
}
result += size(garbage[i]);
}
for (const auto& [_, v] : lookup) {
if (v - 1 >= 0) {
result += travel[v - 1];
}
}
return result;
}
};
// Time: O(n * l), l = max(len(g) for g in garbage) = O(10)
// Space: O(1)
// simulation, prefix sum
class Solution2 {
public:
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
int result = 0;
for (const auto& t : "MPG") {
int curr = 0;
for (int i = 0; i < size(garbage); ++i) {
const int cnt = count(cbegin(garbage[i]), cend(garbage[i]), t);
if (cnt) {
result += curr + cnt;
curr = 0;
}
if (i < size(travel)) {
curr += travel[i];
}
}
}
return result;
}
};