-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmaximum-total-area-occupied-by-pistons.py
64 lines (57 loc) · 1.7 KB
/
maximum-total-area-occupied-by-pistons.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Time: O(h)
# Space: O(h)
import itertools
# line sweep, difference array
class Solution(object):
def maxArea(self, height, positions, directions):
"""
:type height: int
:type positions: List[int]
:type directions: str
:rtype: int
"""
diff = [0]*(2*height+1)
for d, i in itertools.izip(directions, positions):
if d == 'U':
diff[height-i] -= 1
diff[(height-i)+height] += 1
else:
diff[i] += 1
diff[i+height] -= 1
result = total = sum(positions)
cnt = directions.count('U')
for t in xrange(1, len(diff)):
total += -(len(directions)-cnt)+cnt
result = max(result, total)
cnt += diff[t]
return result
# Time: O(nlogn)
# Space: O(n)
import collections
import itertools
# sort, line sweep, difference array
class Solution2(object):
def maxArea(self, height, positions, directions):
"""
:type height: int
:type positions: List[int]
:type directions: str
:rtype: int
"""
diff = collections.defaultdict(int)
for d, i in itertools.izip(directions, positions):
if d == 'U':
diff[height-i] -= 1
diff[(height-i)+height] += 1
else:
diff[i] += 1
diff[i+height] -= 1
result = total = sum(positions)
cnt = directions.count('U')
prev = 0
for t, d in sorted(diff.iteritems()):
total += (t-prev)*(-(len(directions)-cnt)+cnt)
result = max(result, total)
cnt += d
prev = t
return result