Created
June 24, 2020 09:25
-
-
Save LarryKarani/5acf3c3e3077835e7ceaada76874202e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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