-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstockSpan.cpp
46 lines (41 loc) · 1.11 KB
/
stockSpan.cpp
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
//https://practice.geeksforgeeks.org/problems/stock-span-problem-1587115621/1
class Solution
{
public:
//Function to calculate the span of stock’s price for all n days.
vector <int> calculateSpan(int price[], int n)
{
stack<pair<int, int>> s;
vector<int> ans;
for(int i=0; i<n; i++)
{
if(s.size()==0)
{
ans.push_back(-1);
}
else if(s.top().first > price[i] and s.size()>0)
{
ans.push_back(s.top().second);
}
else if(s.size()>0 and s.top().first<=price[i])
{
while(s.size()>0 and s.top().first <= price[i])
s.pop();
if(s.size()==0)
{
ans.push_back(-1);
}
else
{
ans.push_back(s.top().second);
}
}
s.push({price[i], i});
}
for(int i=0;i<n;i++)
{
ans[i]=i-ans[i];
}
return ans;
}
};