Skip to content

Instantly share code, notes, and snippets.

@LarryKarani
Created June 24, 2020 09:25
Show Gist options
  • Save LarryKarani/5acf3c3e3077835e7ceaada76874202e to your computer and use it in GitHub Desktop.
Save LarryKarani/5acf3c3e3077835e7ceaada76874202e to your computer and use it in GitHub Desktop.
#NB used python 3
# 3 Maximum In A stack
class MaxStack:
def __init__(self):
self.elements = []
self.maximums = []
def push(self, val):
self.elements.append(val)
if not self.maximums:
self.maximums.append(val)
else:
self.maximums.append(max(self.maximums[-1], val))
def pop(self):
self.elements.pop()
self.maximums.pop()
def max(self):
if self.maximums:
return self.maximums[-1]
return None
s = MaxStack()
s.push(1)
s.push(2)
s.push(3)
s.push(2)
print(s.max())
# 3
s.pop()
s.pop()
print (s.max())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment