-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path716-Max-Stack.cs
More file actions
76 lines (62 loc) · 1.81 KB
/
Copy path716-Max-Stack.cs
File metadata and controls
76 lines (62 loc) · 1.81 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
71
72
73
74
75
76
// We can achieve the required functionality by maintaining two stacks
// One stack will function normally as a typical stack and handle the regular functions
// Another stack will exclusivly track maxes so far
// O(N) Time for PopMax(), O(1) for all others
// O(N) Space where N is total elems added
public class MaxStack
{
private Stack<int> _stack;
private Stack<int> _maxStack;
public MaxStack()
{
_stack = new Stack<int>();
_maxStack = new Stack<int>();
}
public void Push(int x)
{
_stack.Push(x);
int max = _maxStack.Count > 0 ? _maxStack.Peek() : int.MinValue;
_maxStack.Push(Math.Max(x, max));
}
public int Pop()
{
_maxStack.Pop();
return _stack.Pop();
}
public int Top()
{
return _stack.Peek();
}
public int PeekMax()
{
return _maxStack.Peek();
}
public int PopMax()
{
// Create a buffer that will hold elements that are on top of the max element in the regular stack
// Pop elems from the regular stack and the max stack until we see the top max elem in the reg stack
// Add elems from the buffer to the regular stack again and add the max elem in the max stack to the max stack for each elem in the buffer
var buffer = new Stack<int>();
int max = PeekMax();
while (Top() != max)
{
buffer.Push(Pop());
}
// Remove the max element
Pop();
while (buffer.Count > 0)
{
Push(buffer.Pop());
}
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();
*/