其他分享
首页 > 其他分享> > LeetCode 901. Online Stock Span

LeetCode 901. Online Stock Span

作者:互联网

原题链接在这里:https://leetcode.com/problems/online-stock-span/

题目:

Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.

The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.

Implement the StockSpanner class:

Example 1:

Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]

Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80);  // return 1
stockSpanner.next(60);  // return 1
stockSpanner.next(70);  // return 2
stockSpanner.next(60);  // return 1
stockSpanner.next(75);  // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85);  // return 6

Constraints:

题解:

Have a stack maintain pair of stock price and corresponding span.

When a new price comes in, pop the stack if top of stack price <= current price. Accumlate the span into current span.

And finally return current span and push into stack.

Time Complexity: O(1). Each price is in and out of stack, overral it takes 2*n time for n price. The average is O(1).

Space: O(n).

AC Java:

 1 class StockSpanner {
 2     Stack<int []> stk;
 3     public StockSpanner() {
 4         stk = new Stack<>();
 5     }
 6     
 7     public int next(int price) {
 8         int res = 1;
 9         while(!stk.isEmpty() && stk.peek()[0] <= price){
10             int [] cur = stk.pop();
11             res += cur[1];
12         }
13         
14         stk.push(new int[]{price, res});
15         return res;
16     }
17 }
18 
19 /**
20  * Your StockSpanner object will be instantiated and called as such:
21  * StockSpanner obj = new StockSpanner();
22  * int param_1 = obj.next(price);
23  */

类似Daily Temperatures.

标签:901,Span,price,next,StockSpanner,stockSpanner,return,Stock,stock
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16390205.html