-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path155-min-stack.ts
More file actions
45 lines (39 loc) · 1016 Bytes
/
Copy path155-min-stack.ts
File metadata and controls
45 lines (39 loc) · 1016 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Solution explanation:
* maintain 2 arrays -- one stack, and one which is the current min number at that point
*/
class MinStack {
private stack: number[];
private minStack: number[];
constructor() {
this.stack = new Array();
this.minStack = new Array();
}
push(val: number): void {
this.stack.push(val);
if (this.minStack.length === 0) {
this.minStack.push(val);
} else {
const currMin = Math.min(this.minStack.at(-1) || -Infinity, val);
this.minStack.push(currMin);
}
}
pop(): void {
this.minStack.pop();
this.stack.pop();
}
top(): number {
return this.stack.at(-1) || -Infinity;
}
getMin(): number {
return this.minStack.at(-1) || -Infinity;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(val)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/