Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created January 19, 2021 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieInDen/73dcbc20793b09af5796447194e0c704 to your computer and use it in GitHub Desktop.
Save charlieInDen/73dcbc20793b09af5796447194e0c704 to your computer and use it in GitHub Desktop.
class MaxStack {
// two stack
// one regular stack
// one max stack, keep track latest max
var stack: [Int] = []
var maxStack: [Int] = []
init() {
}
func push(_ x: Int) {
stack.append(x)
maxStack.append(maxStack.isEmpty ? x : max(maxStack.last!, x))
}
func pop() -> Int {
maxStack.removeLast()
return stack.removeLast()
}
func top() -> Int {
return stack.last!
}
func peekMax() -> Int {
return maxStack.last!
}
func popMax() -> Int {
let max = maxStack.last!
var tmp: [Int] = []
while let lastItem = stack.popLast() {
maxStack.removeLast()
if lastItem == max {
print("removed:",lastItem)
break
} else {
tmp.append(lastItem)
}
}
while let lastItem = tmp.popLast() {
self.push(lastItem)
}
return max
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment