-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMax Stack.java
More file actions
66 lines (56 loc) · 1.39 KB
/
Copy pathMax Stack.java
File metadata and controls
66 lines (56 loc) · 1.39 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//time:o(n )
//space:o(n )
class MaxStack {
Stack<Integer> stack;
Stack<Integer> maxStack;
/** initialize your data structure here. */
public MaxStack() {
stack = new Stack<>();
maxStack = new Stack<>();
}
public void push(int x) {
pushHelper(x);
}
public void pushHelper(int x) {
int tempMax = maxStack.isEmpty() ? Integer.MIN_VALUE : maxStack.peek();
if (x > tempMax) {
tempMax = x;
}
stack.push(x);
maxStack.push(tempMax);
}
public int pop() {
maxStack.pop();
return stack.pop();
}
public int top() {
return stack.peek();
}
public int peekMax() {
return maxStack.peek();
}
public int popMax() {
int max = maxStack.peek();
Stack<Integer> temp = new Stack<>();
while (stack.peek() != max) {
temp.push(stack.pop());
maxStack.pop();
}
stack.pop();
maxStack.pop();
while (!temp.isEmpty()) {
int x = temp.pop();
pushHelper(x);
}
return max;
}
}
/**
* Your MaxStack object will be instantiated and called as such:
* MaxStack obj = new MaxStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.peekMax();
* int param_5 = obj.popMax();
*/