-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathStock Span .cpp
More file actions
58 lines (44 loc) · 1.43 KB
/
Copy pathStock Span .cpp
File metadata and controls
58 lines (44 loc) · 1.43 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
// Stack QPS
#include<bits/stdc++.h>
using namespace std;
/*
Stock Span problem is a financial problem where we have a series of N daily price quotes for a stack
and we need to calculate span of stock's price for all N days. You are given an array of length N, where
ith element of array is the price of Stock on ith. Find the span of stock's price on ith day for every 1<=i<=N.
A span of stock's price on a given day i, is the max num of consecutive days before the (i+1)th day for which stock's price on these days is less than or equal to that on the ith day
I/P : 5 30 35 40 38 35
O/P : 1 2 3 1 1 END
*/
int main(){
int n;
cin>>n;
vector<int> prices(n);
for(int i=0;i<n;i++){
cin>>prices[i];
}
vector<int> out(n);
stack<int> stack;
for(int i=0;i<prices.size();i++){
while(!stack.empty() && prices[stack.top()] <= prices[i]){
stack.pop();
}
int j;
if(stack.empty()){
// you could not find a day on the left of the ith day
// where price became greater
j = -1;
}
else{
// you found a day on which the price becomes greater
// than the price on ith day
j = stack.top();
}
//out[i] = stack.empty() ? i-(-1) : i-stack.top();
stack.push(i);
}
for(int i=0;i<out.size();i++){
cout<<out[i]<<" ";
}
cout<<"END";
return 0;
}