-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathSpecial_Stack.java
97 lines (83 loc) · 1.81 KB
/
Special_Stack.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
// { Driver Code Starts
import java.util.Scanner;
import java.util.Stack;
class SpeStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
Stack<Integer> s = new Stack<>();
GfG g = new GfG();
while (!g.isEmpty(s)) {
g.pop(s);
}
while (!g.isFull(s, n)) {
g.push(sc.nextInt(), s);
}
System.out.println(g.min(s));
}
}
}// } Driver Code Ends
/* Complete the function(s) below */
class GfG {
// Space O(1)
int minVal = Integer.MAX_VALUE;
public void push(int a, Stack<Integer> s) {
if (s.isEmpty()) {
minVal = a;
s.push(a);
} else {
if (a < minVal) {
s.push(2 * a - minVal);
minVal = a;
} else {
s.push(a);
}
}
}
public int pop(Stack<Integer> s) {
int pop = s.pop();
if (pop < minVal) {
minVal = 2 * minVal - pop;
}
return pop;
}
public int min(Stack<Integer> s) {
return minVal;
}
public boolean isFull(Stack<Integer> s, int n) {
return s.size() == n;
}
public boolean isEmpty(Stack<Integer> s) {
return s.size() == 0;
}
// Space O(n)
// Stack<Integer> minS = new Stack<>();
// public void push(int a, Stack<Integer> s) {
// if (s.isEmpty()) {
// minS.push(a);
// } else {
// int y = minS.peek();
// if (y < a) {
// minS.push(y);
// } else {
// minS.push(a);
// }
// }
// s.push(a);
// }
// public int pop(Stack<Integer> s) {
// s.pop();
// return minS.pop();
// }
// public int min(Stack<Integer> s) {
// return minS.peek();
// }
// public boolean isFull(Stack<Integer> s, int n) {
// return s.size() == n;
// }
// public boolean isEmpty(Stack<Integer> s) {
// return s.size() == 0;
// }
}