-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack_Example.java
151 lines (122 loc) · 2.63 KB
/
Stack_Example.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;
/**
*
* @author pulkit4tech
*/
public class Stack_Example implements Runnable {
BufferedReader c;
PrintWriter pout;
// static long mod = 1000000007;
public void run() {
try {
c = new BufferedReader(new InputStreamReader(System.in));
pout = new PrintWriter(System.out, true);
solve();
pout.close();
} catch (Exception e) {
pout.close();
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
new Thread(new Stack_Example()).start();
}
void solve() throws Exception {
//balance_paranthesis();
//next_greatest_element();
stock_span();
}
void stock_span(){
int price[] = {10, 4, 5, 90, 120, 80};
calSpan(price);
}
void calSpan(int price[]){
int len = price.length;
Stack<Integer> st = new Stack<>();
int S[] = new int[len];
S[0] = 1;
st.push(0);
for(int i=1;i<len;i++){
while(st.size()!=0 && price[st.peek()]<=price[i]){
st.pop();
}
if(st.size()==0){
S[i] = i+1;
}
else{
S[i] = i - st.peek();
}
st.push(i);
}
for(int i=0;i<len;i++)
pout.print(S[i] + " ");
pout.println();
}
void next_greatest_element(){
int arr[] = {11,13,1,2,3,21,14,2};
printNGE(arr);
}
void printNGE(int arr[]){
int len = arr.length;
Stack<Integer> st = new Stack<>();
st.push(arr[0]);
for(int i=1;i<len;i++){
int next = arr[i];
if(st.size()>0){
int el = st.pop();
while(el<next){
pout.println(el + " --> " + next);
if(st.size()==0)
break;
el = st.pop();
}
if(el>next)
st.push(el);
}
st.push(next);
}
while(st.size()>0){
pout.println(st.pop() + " --> " + -1);
}
}
void balance_paranthesis(){
String exp = "{}({[]})[]";
pout.println(areParenthesisBalnced(exp));
}
boolean isMatchingPair(char char1,char char2){
if(char1 == '(' && char2 == ')')
return true;
if(char1 == '{' && char2 == '}')
return true;
if(char1 == '[' && char2 == ']')
return true;
return false;
}
boolean areParenthesisBalnced(String exp){
int i=0;
Stack<Character> st = new Stack<>();
while(i<exp.length()){
if(exp.charAt(i) == '{' ||
exp.charAt(i) == '[' ||
exp.charAt(i) == '(')
st.push(exp.charAt(i));
if(exp.charAt(i) == '}' ||
exp.charAt(i) == ']' ||
exp.charAt(i) == ')'){
if(st.size()==0)
return false;
if(!isMatchingPair(st.pop(), exp.charAt(i)))
return false;
}
i++;
}
if(st.size()==0)
return true;
else
return false;
}
}