-
Notifications
You must be signed in to change notification settings - Fork 0
/
#2593 findScore.py
44 lines (34 loc) · 1.07 KB
/
#2593 findScore.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
class Solution:
def findScore(self, nums: List[int]) -> int:
# Heap solution
# pq = []
# for i, num in enumerate(nums):
# heapq.heappush(pq, (num, i))
# marked = set()
# ans = 0
# while pq:
# val, i = heapq.heappop(pq)
# if i in marked:
# continue
# marked.add(i)
# marked.add(i - 1)
# marked.add(i + 1)
# ans += val
# return ans
# Monotonic stack solution
stack = []
ans = 0
for num in nums:
if not stack or num < stack[-1]:
stack.append(num)
else:
while stack:
ans += stack.pop()
if stack:
stack.pop() # Double pop to ensure the cliff leading to the local min is marked as well
# Deal with remaining monotonically decreasing values in the stack
while stack:
ans += stack.pop()
if stack:
stack.pop()
return ans