Stock Span
On the sixth day when the price of the stock was 75, the span came out to be 4, because the last 4 prices(including the current price of 75) were less than the current or the sixth day's price.
Similarly, we can deduce the remaining results.
The first line of input contains an integer N, denoting the total number of days.
The second line of input contains the stock prices of each day. A single space will separate them.
The only line of output will print the span for each day's stock price. A single space will separate them.
You are not required to print the expected output explicitly. It has already been taken care of.
0 <= N <= 10^7
1 <= X <= 10^9
Where X denotes the stock's price for a day.
Time Limit: 1 second
4
10 10 10 10
1 1 1 1
8
60 70 80 100 90 75 80 120
1 2 3 4 1 1 2 8
#include<stack>int* stockSpan(int *price, int size) { // Write your code here stack <int> s; int *output=new int[size]; output[0]=1; s.push(0); for(int i=1;i<size;i++) { while(!s.empty()and price[i]>price[s.top()] ) { s.pop(); } if(s.empty()) { output[i]=i+1; s.push(i); } else { output[i]=i-s.top(); s.push(i); } } return output;}
Comments
Post a Comment