Skip to content

Commit 606b5c7

Browse files
committed
Update 716_Max_Stack.java
1 parent e57dd42 commit 606b5c7

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

Design/716_Max_Stack.java

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,45 @@
11
class MaxStack {
2-
private Stack<Integer> stack, maxStack;
2+
private Stack<Integer> st, maxSt;
33

44
public MaxStack() {
5-
stack = new Stack<>();
6-
maxStack = new Stack<>();
5+
st = new Stack<>();
6+
maxSt = new Stack<>();
77
}
88

99
public void push(int x) {
10-
int tempMax = maxStack.isEmpty() ? Integer.MIN_VALUE : maxStack.peek();
10+
int max = maxSt.isEmpty() ? Integer.MIN_VALUE : maxSt.peek();
11+
max = Math.max(max, x);
1112

12-
if (x > tempMax) {
13-
tempMax = x;
14-
}
15-
16-
maxStack.push(tempMax);
17-
stack.push(x);
13+
st.push(x);
14+
maxSt.push(max);
1815
}
1916

2017
public int pop() {
21-
maxStack.pop();
22-
return stack.pop();
18+
maxSt.pop();
19+
return st.pop();
2320
}
2421

2522
public int top() {
26-
return stack.peek();
23+
return st.peek();
2724
}
2825

2926
public int peekMax() {
30-
return maxStack.peek();
27+
return maxSt.peek();
3128
}
3229

3330
public int popMax() {
3431
int max = peekMax();
3532

3633
Stack<Integer> buffer = new Stack<>();
3734

38-
while (stack.peek() != max) {
39-
buffer.push(stack.pop());
40-
maxStack.pop();
35+
while (top() != max) {
36+
buffer.push(pop());
4137
}
42-
4338
pop();
44-
4539
while (!buffer.isEmpty()) {
4640
push(buffer.pop());
4741
}
42+
4843
return max;
4944
}
5045
}

0 commit comments

Comments
 (0)