-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStockSpan.cpp
More file actions
69 lines (61 loc) · 1.21 KB
/
StockSpan.cpp
File metadata and controls
69 lines (61 loc) · 1.21 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
/*
Array
___________________________________
100 | 80 | 60 | 70 | 60 | 75 | 85 |
____|____|____|____|____|____|____|
Vector
-1, 0, 1, 1, 3, 1, 0
*/
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
class StockSpan {
public :
void stockSpan(int arr[], int n){
stack <pair<int, int>> s;
vector <int> v;
for(int i = 0; i < n; i++){
if(s.empty()){
v.push_back(-1);
}
else
if(s.size() > 0 && s.top().first > arr[i]){
v.push_back(s.top().second);
}
else
if(s.size() > 0 && s.top().first <= arr[i]){
while(s.size() > 0 && s.top().first <= arr[i]){
s.pop();
}
if(s.empty()){
v.push_back(-1);
}
else{
v.push_back(s.top().second);
}
}
s.push({arr[i], i});
} // end of for loop
for(int i = 0; i < n; i++){
v[i] = abs(i - v[i]);
}
for(auto it : v){
cout<<it<<" ";
}
cout<<endl;
}
};
int main(){
cout<<"Enter the size of the array"<<endl;
int n;
cin>>n;
int arr[n];
cout<<"Enter array elemets "<<endl;
for(int i = 0; i < n; i++){
cin>>arr[i];
}
StockSpan obj;
obj.stockSpan(arr, n);
return 0;
}