[Algorithm] Min Max Stack
Write a MinMaxStack class for a Min Max Stack. The class should support:
- Pushing and popping values on and off the stack.
- Peeking at the value at the top of the stack.
- Getting both the minimum and the maximum values in the stack at any given point in time.
All class methods, when considered independently, should run in constant time and with constant space.
// All operations below are performed sequentially.
MinMaxStack(): - // instantiate a MinMaxStack
push(5): -
getMin(): 5
getMax(): 5
peek(): 5
push(7): -
getMin(): 5
getMax(): 7
peek(): 7
push(2): -
getMin(): 2
getMax(): 7
peek(): 2
pop(): 2
pop(): 7
getMin(): 5
getMax(): 5
peek(): 5
package main
type MinMaxStack struct {
data []int
minMaxStack []entry
}
type entry struct {
max int
min int
}
func NewMinMaxStack() *MinMaxStack {
return &MinMaxStack{}
}
func (stack *MinMaxStack) Peek() int {
return stack.data[len(stack.data)-1]
}
func (stack *MinMaxStack) Pop() int {
stack.minMaxStack = stack.minMaxStack[:len(stack.minMaxStack)-1]
output := stack.data[len(stack.data)-1]
stack.data = stack.data[:len(stack.data)-1]
return output;
}
func (stack *MinMaxStack) Push(number int) {
newMinMax := entry{min: number, max: number}
if len(stack.minMaxStack) > 0 {
lastMinMax := stack.minMaxStack[len(stack.minMaxStack) - 1]
newMinMax.min = min(lastMinMax.min, number)
newMinMax.max = max(lastMinMax.max, number)
}
stack.minMaxStack = append(stack.minMaxStack, newMinMax)
stack.data = append(stack.data, number)
}
func (stack *MinMaxStack) GetMin() int {
return stack.minMaxStack[len(stack.minMaxStack)-1].min
}
func (stack *MinMaxStack) GetMax() int {
return stack.minMaxStack[len(stack.minMaxStack)-1].max
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a < b {
return b
}
return a
}