-
Notifications
You must be signed in to change notification settings - Fork 892
/
problem_043.py
53 lines (46 loc) · 954 Bytes
/
problem_043.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
class Stack:
def __init__(self):
self.stack = []
self.max_stack = []
def push(self, val):
self.stack.append(val)
if not self.max_stack or val > self.stack[self.max_stack[-1]]:
self.max_stack.append(len(self.stack) - 1)
def pop(self):
if not self.stack:
return None
if len(self.stack) - 1 == self.max_stack[-1]:
self.max_stack.pop()
return self.stack.pop()
def max(self):
if not self.stack:
return None
return self.stack[self.max_stack[-1]]
s = Stack()
s.push(1)
s.push(3)
s.push(2)
s.push(5)
assert s.max() == 5
s.pop()
assert s.max() == 3
s.pop()
assert s.max() == 3
s.pop()
assert s.max() == 1
s.pop()
assert not s.max()
s = Stack()
s.push(10)
s.push(3)
s.push(2)
s.push(5)
assert s.max() == 10
s.pop()
assert s.max() == 10
s.pop()
assert s.max() == 10
s.pop()
assert s.max() == 10
s.pop()
assert not s.max()