-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxStack.java
More file actions
70 lines (61 loc) · 1.25 KB
/
MaxStack.java
File metadata and controls
70 lines (61 loc) · 1.25 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
67
68
69
70
import java.util.Stack;
class MaxStack
{
Stack<Integer> stack = new Stack<>();
int _max = Integer.MIN_VALUE;
/** initialize your data structure here. */
public MaxStack()
{
}
public void push( int x )
{
_max = Math.max( _max, x );
stack.push( x );
}
public int pop()
{
if ( stack.peek() != _max )
return stack.pop();
// update max value
int m = stack.pop(); // m happens to be max
_max = Integer.MIN_VALUE;
for ( int k : stack )
// update max
_max = Math.max( _max, k );
return m;
}
public int top()
{
return stack.peek();
}
public int peekMax()
{
return _max;
}
public int popMax()
{
Stack<Integer> newStack = new Stack<>();
while ( stack.peek() != _max )
newStack.add( stack.pop() );
int m = stack.pop(); // m is max to be popped
// update max value
_max = Integer.MIN_VALUE;
for ( int k : stack )
_max = Math.max( _max, k );
while ( !newStack.isEmpty() )
{
stack.add( newStack.pop() );
_max = Math.max( _max, stack.peek() );
}
return m;
}
}
/**
* 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();
*/