-
Notifications
You must be signed in to change notification settings - Fork 1
/
096_Online Stock Span.cpp
56 lines (41 loc) · 977 Bytes
/
096_Online Stock Span.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
47
48
49
50
51
52
53
54
55
56
// Time Complexity -> O(n^2)
// Space Complexity -> O(n)
#include <bits/stdc++.h>
vector<int> findSpans(vector<int> &price) {
// Write your code here.
int n = price.size();
vector<int> ans;
for(int i = 0; i < n; ++i)
{
int cnt = 0;
for(int j = i; j >= 0; --j)
{
if(price[j] <= price[i])
++cnt;
else
break;
}
ans.push_back(cnt);
}
return ans;
}
// Time Complexity -> O(n)
// Space Complexity -> O(2n)
#include <bits/stdc++.h>
vector<int> findSpans(vector<int> &price) {
// Write your code here.
int n = price.size();
vector<int> ans(n,0);
stack<int> st;
for(int i = 0; i < n; ++i)
{
while(!st.empty() and price[st.top()] <= price[i])
st.pop();
if(st.empty())
ans[i] = i+1;
else
ans[i] = i - st.top();
st.push(i);
}
return ans;
}