Leetcode 901 Online Stock Span
Problem
Write a class StockSpanner which 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 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 [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].
Example 1:
1 | Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]] |
Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today’s price of 75) were less than or equal to today’s price.
Note:
- Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5.
- There will be at most 10000 calls to StockSpanner.next per test case.
- There will be at most 150000 calls to StockSpanner.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
解题思路
本题考验的是对Java Stack类的熟练使用。
O(n)复杂度思路
不难发现,运用两个Stack可以灵活的将数组中的数字进行遍历比较,从而得出结果。但是由于Leetcode对于时间复杂度要求较高,因此同为O(n)算法,需要最大化的优化其系数,从而通过时间限制测试。
Leetcode solution中提出的一种简化计算的方法
在仔细分析对比数组的计算结果后,不难得出以下几个结论:
- 当数组元素值减少时,权重结果为1;
- 当数组元素值增加时,倒推前面小于该值的连续区间可以替换成局部最大值和其局部权重weight。局部最大值即当前元素值;而最末元素的权重,正好是其前面小于该值的连续区间的权重和+1。权重值则为我们需要的返回值。
以Example中的数组为例,用Stack<int[]>表示分步计算结果为:
- [100, 1]
- [100, 1], [80, 1]
- [100, 1], [80, 1], [60, 1]
- [100, 1], [80, 1], [70, 2]
- [100, 1], [80, 1], [70, 2], [60, 1]
- [100, 1], [80, 1], [75, 4]
- [100, 1], [85, 6]
…
实现技巧
需要注意的本解法并没有简化时间复杂度,因为在最差情况下(数列递减),计算的复杂度为O(n)。代码如下:
1 | class StockSpanner { |