- No, it's clear from problem description.
Input:
Output:
Input:
Output:
We keep the peek value and current min via using two stack, and manipulate at the same time.
// 1. Value stack
// 2. Minimum stack
|-2| |-3|
|-1| |-3|
|-3| |-3|
| 0| | 0|
|__| |__|
class MinStack() {
private val valueStack = Stack<Int>()
private val minStack = Stack<Int>()
fun push(`val`: Int) {
valueStack.push(`val`)
if (minStack.isEmpty()) {
minStack.push(`val`)
} else {
minStack.push(if (minStack.peek() > `val`) `val` else minStack.peek())
}
}
fun pop() {
valueStack.pop()
minStack.pop()
}
fun top(): Int = valueStack.peek()
fun getMin(): Int = minStack.peek()
}