Online Stock Span in C++

C++Server Side ProgrammingProgramming

Suppose we have an API, that collects daily price quotes for some stock, and returns the span of that stock's price for the current day. Here the span of the stock's price today is defined as −

  • The maximum number of consecutive days (starting from today and going backwards) where the price of the stock was less than or equal to today's price.

For example, if we see 7 days stock share records like [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6]. We have to write the actual module for that API, that will be used when this module will be called

To solve this, we will follow these steps −

  • define two arrays st, v and counter, set counter as 0
  • increase counter by 1
  • while st is not empty and price >= v[stack top element]
    • pop from stack.
  • ans := counter when stack is empty, otherwise ans := counter – stack top
  • insert price in the v
  • insert counter into st
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class StockSpanner {
   public:
   vector <int> st;
   int counter;
   vector <int> v;
   StockSpanner() {
      counter = 0;
   }
   int next(int price) {
      counter++;
      while(!st.empty() && price >= v[st.back() - 1])st.pop_back();
      int ans = st.empty() ? counter : counter - st.back();
      v.push_back(price);
      st.push_back(counter);
      return ans ;
   }
};
main(){
   StockSpanner ob;
   cout <<(ob.next(100)) << endl;
   cout <<(ob.next(80)) << endl;
   cout <<(ob.next(60)) << endl;
   cout <<(ob.next(70)) << endl;
   cout <<(ob.next(60)) << endl;
   cout <<(ob.next(75)) << endl;
   cout <<(ob.next(85)) << endl;
}

Input

Initialize the class, then call next() method using different values. See the main() method

Output

1
1
1
2
1
4
6
raja
Updated on 30-Apr-2020 07:33:05

Advertisements