Write a class
The span of the stock’s price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today’s price.
For example, if the price of a stock over the next 7 days were
Example 1:
Note:
- Calls to
StockSpanner.next(int price) will have1 <= price <= 10^5 . - There will be at most
10000 calls toStockSpanner.next per test case. - There will be at most
150000 calls toStockSpanner.next across all test cases. - The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.
Solution
We can solve using Stack, maintain stack of number and accumulated span for the current number.
Before pushing current entry to the stack, check top entry from the stack, if its smaller then current entry then pop it and add span to the current span.
Once top element is higher then current number then push the final entry to the stack.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import java.util.Stack; public class StockSpanner { private Stack<int[]> stack; public StockSpanner() { stack = new Stack<>(); } public int next(int price) { int cnt=1; while(stack.size()>0 && stack.peek()[0]<price) { cnt+=stack.pop()[1]; } int [] newEnt=new int[2]; newEnt[0]=price; newEnt[1]=cnt; stack.push(newEnt); return cnt; } public static void main(String s[]) { StockSpanner st = new StockSpanner(); System.out.println(st.next(100)); System.out.println(st.next(80)); System.out.println(st.next(60)); System.out.println(st.next(65)); System.out.println(st.next(70)); System.out.println(st.next(60)); System.out.println(st.next(75)); System.out.println(st.next(85)); } } |
Output
Complexity Analysis
Time complexity: O(N).Space Complexity: O(N).
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.