-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
beautiful-towers-i.py
31 lines (30 loc) · 1020 Bytes
/
beautiful-towers-i.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
# Time: O(n)
# Space: O(n)
# mono stack
class Solution(object):
def maximumSumOfHeights(self, maxHeights):
"""
:type maxHeights: List[int]
:rtype: int
"""
left = [0]*len(maxHeights)
stk = [-1]
curr = 0
for i in xrange(len(maxHeights)):
while stk[-1] != stk[0] and maxHeights[stk[-1]] >= maxHeights[i]:
j = stk.pop()
curr -= (j-stk[-1])*maxHeights[j]
curr += (i-stk[-1])*maxHeights[i]
stk.append(i)
left[i] = curr
stk = [len(maxHeights)]
result = right = curr = 0
for i in reversed(xrange(len(maxHeights))):
while stk[-1] != stk[0] and maxHeights[stk[-1]] >= maxHeights[i]:
j = stk.pop()
curr -= (stk[-1]-j)*maxHeights[j]
curr += (stk[-1]-i)*maxHeights[i]
stk.append(i)
right = curr
result = max(result, left[i]+right-maxHeights[i])
return result