forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-amount-of-time-to-collect-garbage.py
44 lines (41 loc) · 1.23 KB
/
minimum-amount-of-time-to-collect-garbage.py
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
# Time: O(n * l), l = max(len(g) for g in garbage) = O(10)
# Space: O(1)
# simulation, prefix sum
class Solution(object):
def garbageCollection(self, garbage, travel):
"""
:type garbage: List[str]
:type travel: List[int]
:rtype: int
"""
result = 0
lookup = {}
for i in xrange(len(garbage)):
for c in garbage[i]:
lookup[c] = i
if i+1 < len(travel):
travel[i+1] += travel[i]
result += len(garbage[i])
result += sum(travel[v-1] for _, v in lookup.iteritems() if v-1 >= 0)
return result
# Time: O(n * l), l = max(len(g) for g in garbage) = O(10)
# Space: O(1)
# simulation, prefix sum
class Solution2(object):
def garbageCollection(self, garbage, travel):
"""
:type garbage: List[str]
:type travel: List[int]
:rtype: int
"""
result = 0
for t in 'MPG':
curr = 0
for i in xrange(len(garbage)):
cnt = garbage[i].count(t)
if cnt:
result += curr+cnt
curr = 0
if i < len(travel):
curr += travel[i]
return result