π One-stop destination for all your technical interview Preparation π
The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stockβs price for all n days. (Find consecutive smaller or equal to element from left i.e. next greater to left)
vector<long long> stockSpan(vector<long long> arr, int n)
{
vector<long long> v;
stack<pair<long long, long long>> s;
for (auto i = 0; i < n; i++)
{
// if stack is empty
if (s.empty())
{
v.push_back(-1);
}
// else if stack not empty and top is greater than arr[i]
else if (!s.empty() && s.top().first > arr[i])
{
v.push_back(s.top().second);
}
// else if stack is not empty and top is less than arr[i]
else if (!s.empty() && s.top().first <= arr[i])
{
// pop untill we get greater element or stack is empty
while (!s.empty() && s.top().first <= arr[i])
{
s.pop();
}
// if stack is empty else push top()
if (s.empty())
{
v.push_back(-1);
}
else
{
v.push_back(s.top().second);
}
}
// push pair in stack
s.push(make_pair(arr[i], i));
}
// vector contains index of greater element to right.
// update vector with correct values i.e. i - v[i]
for (auto i = 0; i < n; i++)
{
v[i] = i - v[i];
}
return v;
}