-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_stack.py
More file actions
46 lines (35 loc) · 1.06 KB
/
max_stack.py
File metadata and controls
46 lines (35 loc) · 1.06 KB
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
# Stack With Maximum
# Author: jerrybelmonte
import sys
class StackWithMax:
def __init__(self):
self.__stack = []
self.__max_stack = []
def push(self, value):
self.__stack.append(value)
if not self.__max_stack:
self.__max_stack.append(value)
elif value >= self.__max_stack[-1]:
self.__max_stack.append(value)
def pop(self):
assert (len(self.__stack))
value = self.__stack.pop()
assert (len(self.__max_stack))
if value == self.__max_stack[-1]:
self.__max_stack.pop()
def max(self):
assert (len(self.__max_stack))
return self.__max_stack[-1]
if __name__ == '__main__':
stack = StackWithMax()
num_queries = int(sys.stdin.readline())
for _ in range(num_queries):
query = sys.stdin.readline().split()
if query[0] == "push":
stack.push(int(query[1]))
elif query[0] == "pop":
stack.pop()
elif query[0] == "max":
print(stack.max())
else:
assert 0