Skip to content

Commit e4d9ba1

Browse files
committed
Stock span problem
1 parent 8604dc3 commit e4d9ba1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Stack/StockSpan.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <vector>
4+
using namespace std;
5+
6+
int main()
7+
{
8+
// stock prices
9+
vector<int> price = {100, 80, 60, 70, 60, 75, 85};
10+
11+
vector<int> ans(price.size(), 0);
12+
stack<int> s;
13+
14+
for (int i = 0; i < price.size(); i++)
15+
{
16+
while (s.size() > 0 && price[s.top()] <= price[i]) // to remove leeser values
17+
{
18+
s.pop();
19+
}
20+
21+
if (s.empty()) // no previous high value
22+
{
23+
ans[i] = i + 1;
24+
}
25+
else
26+
{
27+
ans[i] = i - s.top();
28+
}
29+
30+
s.push(i);
31+
}
32+
33+
for (int val : ans)
34+
{
35+
cout << val << " ";
36+
}
37+
cout << endl;
38+
39+
return 0;
40+
}

Stack/StockSpan.exe

96.3 KB
Binary file not shown.

0 commit comments

Comments
 (0)