My solution to the question works well except for the pop max function And I supposed to retrieve the maximum element on the stock and remove it. It feels against this test case. How do I fix it?
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
Implement the MaxStack
class:
- MaxStack()
Initializes the stack object. - void push(int x)
Pushes element x
onto the stack. - int pop()
Removes the element on top of the stack and returns it. - int top()
Gets the element on the top of the stack without removing it. - int peekMax()
Retrieves the maximum element in the stack without removing it. - int popMax()
Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the top-most one.
TestCase:
Input: ["MaxStack","push","push","popMax","peekMax"]
[,[5],[1],,]
Output: [null,null,null,5,-1]
Expected: [null,null,null,5,1]
class MaxStack {
var stack = [Int]()
var maxStack = [Int]()
/** initialize your data structure here. */
init() {}
func push(_ x: Int) {
stack.append(x)
if maxStack.isEmpty || x >= maxStack.last! {
maxStack.append(x)
}
}
func pop() -> Int {
if let last = stack.popLast() {
if last == maxStack.last! {
maxStack.removeLast()
}
return last
}
return -1
}
func top() -> Int {
if let last = stack.last {
return last
}
return -1
}
func peekMax() -> Int {
if let last = maxStack.last {
return last
}
return -1
}
func popMax() -> Int {
if let last = maxStack.popLast() {
var max = last
while let last = stack.popLast(), last != max {
if last > max {
max = last
}
}
return max
}
return -1
}
}