-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinMaxInStack.java
122 lines (112 loc) · 2.98 KB
/
MinMaxInStack.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class MinMaxInStack {
public static class MinStack {
Stack<Integer> data;
int min;
int max;
public MinStack() {
data = new Stack<>();
}
int size() {
return data.size();
}
void push(int val) {
if(data.isEmpty())
{
data.push(val);
min = val;
max = val;
}
else if(val < min)
{
data.push(val + val - min);
min = val;
}
else if(val > max)
{
data.push(val + val - max);
max = val;
}
else
{
data.push(val);
}
}
int pop() {
if(data.peek()<min)
{
int val = min;
min = 2 * min - data.pop();
return val;
}
else if(data.peek()>max)
{
int val = max;
max = 2 * max - data.pop();
return val;
}
else
{
return data.pop();
}
}
int top() {
if(data.peek() < min)
{
return min;
}
else if(data.peek() > min)
{
return max;
}
else
{
return data.peek();
}
}
int min() {
return min;
}
int max() {
// write your code here
return max;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
MinStack st = new MinStack();
String str = br.readLine();
while (!str.equals("quit")) {
if (str.startsWith("push")) {
int val = Integer.parseInt(str.split(" ")[1]);
st.push(val);
} else if (str.startsWith("pop")) {
int val = st.pop();
if (val != -1) {
System.out.println(val);
}
} else if (str.startsWith("top")) {
int val = st.top();
if (val != -1) {
System.out.println(val);
}
} else if (str.startsWith("size")) {
System.out.println(st.size());
} else if (str.startsWith("min")) {
int val = st.min();
if (val != -1) {
System.out.println(val);
}
}
else if (str.startsWith("max")) {
int val = st.max();
if (val != -1) {
System.out.println(val);
}
}
str = br.readLine();
}
}
}