Stock Span Problem (Solution in Java)

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 the span of stock’s price for all n days.
The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day(including), for which the price of the stock on the current day is less than or equal to its price on the given day.
For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}.

Explanation to the given example:
On 0th day only the current day where we find that stock price is less than or equal to it so for 1 consecutive day(current day) this happens.
On 1st day only the current day where we find that stock price is less than or equal to it so for 1 consecutive day(current day) this happens.
On 2nd day only the current day where we find that stock price is less than or equal to it so for 1 consecutive day(current day) this happens.
Now on 3rd day we observe that stock price for last two consecutive days is less than or equal to current day i.e. (60, 70) thus count is 2
On 4th day only the current day where we find that stock price is less than or equal to it so for 1 consecutive day(current day) this happens.
On 5th day we observe that stock price for last four consecutive days is less than or equal to current day i.e. (60, 70, 60, 75) thus count is 4.
On 6th day we observe that stock price for last six consecutive days is less than or equal to current day i.e. (80, 60, 70, 60, 75, 85) thus count is 6.


Thank you so much for reading this article, if you like this question please share this with your friends who love programming. And if you have questions or feedback please drop a comment.

To solve more problems on Array and String, please check out these articles "Top 10 Array Interview Questions" and "Top 10 String Interview Questions".

All the Best!

Comments

Popular posts from this blog

Four Sum Problem (4sum) Solution in Java, Python, C++

Find the length of the longest substring without repeating character

Reverse Words in a Sentence Without using any Library