-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstock_span.cpp
More file actions
73 lines (63 loc) · 1.59 KB
/
Copy pathstock_span.cpp
File metadata and controls
73 lines (63 loc) · 1.59 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
70
71
72
73
/*
Problem Link : https://www.pepcoding.com/resources/online-java-foundation/stacks-and-queues/stock_span/topic
You are given a number n, representing the size of array a.
You are given n numbers, representing the prices of a share on n days.
You are required to find the stock span for n days.
Stock span is defined as the number of days passed between
the current day and the first day before today when the price was higher than today.
*/
/*
Note : NGE on left , Number of days b/w NGE on left and current number
*/
// Solution : https://youtu.be/0BsPlzqksZQ?list=PL-Jc9J83PIiFj7YSPl2ulcpwy-mwj1SSk
#include<iostream>
#include<fstream>
#include<vector>
#include<iterator>
#include<algorithm>
#include<stack>
#include<queue>
#include<deque>
#include<utility>
#include<unordered_map>
#include<set>
#include<map>
#include<unordered_set>
#include<string>
#include<limits.h>
using namespace std;
#define ll long long int
const int mod=1e9+7;
int main()
{
int n;
cin>>n;
vector<int> arr(n,0);
vector<int> NGE(n,-1);//This vector store the indices of Previous Greater Element
for(int i=0;i<n;i++)
cin>>arr[i];
stack<int> st;
for(int i=0;i<n;i++)
{
if(st.empty())
{
st.push(i);
}
else
{
while(!st.empty() && arr[st.top()]<=arr[i])
st.pop();
if(!st.empty())
NGE[i]=st.top();
st.push(i);
}
}
for(int i=0;i<n;i++)
{
//This loop prints the span
if(NGE[i]==-1)
cout<<(i+1)<<"\n";
else
cout<<(i-NGE[i])<<"\n";
}
}