|
| 1 | +/* |
| 2 | + * Stock span Problem |
| 3 | + * |
| 4 | + * Given : We have series of n daily price quotes for a stock. |
| 5 | + * |
| 6 | + * Required: We need to calculate **span** of stock's price for all n days. |
| 7 | + * Span for ith day is defined as **maximum** number of consecutive days, |
| 8 | + * for which the price of the stock was less than or equal to ith day. |
| 9 | + * |
| 10 | + * Example: For stock quotes {100, 60, 70, 65, 80, 85} span will be {1, 1, 2, 1, 4, 5}. |
| 11 | + * Span for day 1 is always 1, now for day 2 stock is at 60, and there is no day befor it when stock was less than 60. |
| 12 | + * So span remains 1. For day 3, the stock is priced at 70, so its span is 2, as previous day it was 60, and so on. |
| 13 | + * Refer readme of for approaches. |
| 14 | + */ |
| 15 | + |
| 16 | +#include <iostream> |
| 17 | +#include <stack.h> |
| 18 | + |
| 19 | +void stock_spans( int *prices, int *spans, int days ) |
| 20 | +{ |
| 21 | + algo::Stack<int> st; |
| 22 | + |
| 23 | + //pushing day one to stack ( days are 0 indexed ) |
| 24 | + st.push(0); |
| 25 | + |
| 26 | + //span for day 1 |
| 27 | + spans[0] = 1; |
| 28 | + |
| 29 | + //span for rest of the days |
| 30 | + for ( int i = 1; i < days; ++i ) |
| 31 | + { |
| 32 | + // Pop till the day stock price was greater than today and stack is not emptuy. |
| 33 | + while ( !st.empty() && prices[i] >= prices[st.top()] ) |
| 34 | + { |
| 35 | + st.pop(); |
| 36 | + } |
| 37 | + |
| 38 | + /* |
| 39 | + * If stack has emptied, then price[i] is the largest of price we have seen |
| 40 | + * so far, else price[i] is greater than price on the day which is on top |
| 41 | + * of stack. |
| 42 | + */ |
| 43 | + spans[i] = (st.empty()) ? ( i + 1 ) : (i - st.top()) ; |
| 44 | + |
| 45 | + //push today on stack. |
| 46 | + st.push(i); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | + |
| 51 | +void printPricesSpans( int *prices, int *spans, int days ) |
| 52 | +{ |
| 53 | + for ( int i = 0; i < days; ++i ) |
| 54 | + { |
| 55 | + std::cout << "Day: " << (i+1) |
| 56 | + << " Price: " << prices[i] |
| 57 | + << " Span: " << spans[i] |
| 58 | + << std::endl; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | + |
| 63 | +int main() |
| 64 | +{ |
| 65 | + int prices[]= { 100, 60, 70, 65, 80, 85 }; |
| 66 | + int *spans = new int[6]; |
| 67 | + stock_spans(prices, spans, 6); |
| 68 | + printPricesSpans( prices, spans, 6 ); |
| 69 | + return 0; |
| 70 | +} |
0 commit comments