chore(CPlusPlus): add stock span problem (#649)

Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com>
pull/652/head
DEBJIT 2021-12-14 00:06:34 +05:30 committed by GitHub
parent 927da7a9ab
commit efe35f5321
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 71 additions and 0 deletions

View File

@ -86,6 +86,7 @@
- [Reversing Stack](Stacks/reverse-stack.cpp) - [Reversing Stack](Stacks/reverse-stack.cpp)
- [Stack using Array](Stacks/stack-using-array.cpp) - [Stack using Array](Stacks/stack-using-array.cpp)
- [Infix to postfix expression conversion](Stacks/infix-to-postfix.cpp) - [Infix to postfix expression conversion](Stacks/infix-to-postfix.cpp)
- [Stock Span Problem using Stacks](Stacks/stock-span-problem.cpp)
## Sorting ## Sorting

View File

@ -0,0 +1,70 @@
/*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 stocks price for all n days.*/
/*The span Si of the stocks price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than its price on the given day.*/
// C++ linear time solution for stock span problem
#include <bits/stdc++.h>
using namespace std;
// A stack based efficient method to calculate
// stock span values
void calculateSpan(const vector<int> price, const int n,vector<int>& S)
{
// Create a stack and push index of first
// element to it
stack<int> st;
st.push(0);
// Span value of first element is always 1
S.push_back(1);
// Calculate span values for rest of the elements
for (int i = 1; i < n; i++) {
// Pop elements from stack while stack is not
// empty and top of stack is smaller than
// price[i]
while (!st.empty() && price[st.top()] < price[i])
st.pop();
// If stack becomes empty, then price[i] is
// greater than all elements on left of it,
// i.e., price[0], price[1], ..price[i-1]. Else
// price[i] is greater than elements after
// top of stack
int x = (st.empty()) ? (i + 1) : (i - st.top());
S.push_back(x);
// Push this element to stack
st.push(i);
}
}
// A utility function to print elements of array
void printArray(const vector<int>& arr,const int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above function
int main()
{
vector<int> price;
int n;
//Enter the size of price
cin>>n;
vector<int> S;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
price.push_back(x);
}
// Fill the span values in array S[]
calculateSpan(price, n, S);
// print the calculated span values
printArray(S, n);
return 0;
}