-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_stack.py
More file actions
43 lines (34 loc) · 733 Bytes
/
Copy pathmax_stack.py
File metadata and controls
43 lines (34 loc) · 733 Bytes
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
# Design a stack that supports `push`, `pop`, `top`, and retrieving the maximum
# element in constant time.
# - `push(x)` - Push element `x` onto stack
# - `pop()` - Removes the element on top of the stack
# - `top()` - Get the top element (sometimes referred to as "peek")
# - `get_max()` - Retrieve the maximum element in the stack
stack = []
max = []
def push(x):
stack.append(x)
if max:
if x > max[-1]:
max.append(x)
else:
max.append(x)
def pop():
if stack[-1] == max[-1]:
max.pop()
stack.pop()
def top():
return stack[-1]
def get_max():
return max[-1]
push(3)
push(6)
push(4)
pop()
push(4)
push(8)
push(1)
top()
print(stack)
print(top())
print(get_max())