-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathMinStack.java
More file actions
60 lines (51 loc) · 1.07 KB
/
MinStack.java
File metadata and controls
60 lines (51 loc) · 1.07 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
package Stacks;
import java.util.Stack;
/**
* Author - archit.s
* Date - 25/10/18
* Time - 11:26 AM
*/
public class MinStack {
private Stack<Integer> values = new Stack<>();
private int minValue = -1;
public void push(int x) {
if(values.empty()){
values.push(x);
minValue = x;
}
else{
if( x < minValue){
values.push(2*x - minValue);
minValue = x;
}
else{
values.push(x);
}
}
}
public void pop() {
if(values.empty()){
return;
}
int temp = values.peek();
values.pop();
if(temp < minValue){
minValue = 2*minValue - temp;
}
}
public int top() {
if(values.empty()){
return -1;
}
if(values.peek()<minValue){
return minValue;
}
return values.peek();
}
public int getMin() {
if(values.empty()){
return -1;
}
return minValue;
}
}