Online Stock Span
For each new day's stock price, count how many days in a row the price has been at or below it.
Write a class StockSpannernext(price)
Example 1
Output: 1, 1, 1, 2, 1, 4, 6
Explanation: for 75, the prices going back are 75, 60, 70, 60, then 80 stops the count: span 4.
The Idea
Think of someone watching a stock's price each evening and asking: how many days in a row has the price been at or below today's level? They count back from today and stop at the first day with a higher price. That count, today included, is the span.
Take the prices from the example, one per day. On day 4 the price is 70. Day 3 had 60, which is lower, and day 2 had 80, which is higher, so the count stops at 2. On day 6 the price is 75. Going back, 60, 70 and 60 are all at most 75, and 80 stops the count, so the span is 4.
The simple way does exactly that: keep every price and walk back for each new one. But when the price rises every day, each call walks back over all the earlier days. Could a call skip over days that an earlier call already counted?
It can. On day 4 we learned that 70 stands for 2 days, day 3 and day 4, because 60 was at most 70. On day 6, once we see that 70 is at most 75, day 3 must be at most 75 too. So we can add 70's span of 2 in one step, without looking at day 3 again.
To do that, we keep the earlier days on a stack: a pile of entries where a new entry goes on top, and only the top entry can be read or removed. Each entry holds a price and its span. Look at the picture below.
On the left, day 6, the price 75, is the orange bar, and the bracket under days 3 to 6 marks its span of 4 days. Day 2, with 80, is where the count stops. In the column labelled "stack before", the top entry is price 60, span 1, for day 5. Below it, price 70, span 2 stands for days 3 and 4.
Both entries are at most 75, so they come off the stack, and their spans, 1 and 2, are added to today's 1. The next entry, price 80, span 1, is higher, so it stays. The column labelled "stack after next(75)" has price 75, span 4 on top.
Can the removed entries ever be needed again? A later count that reaches back past day 6 needs a price of at least 75, which is also at least 60 and 70. That count simply adds 75's span of 4, which already includes their days. So the stack only keeps days that can still stop a count, and its prices fall from the bottom to the top. A stack whose entries always stay in sorted order like this is called a
Solution Approach
How much does the stack save over the simple walk back? Once that is clear, the stack version needs two decisions: what each entry holds, and when an entry comes off the stack.
Walking back day by day
What does the direct way cost? It keeps every price in a list, and each call steps back from the end while the price there is at most today's. When prices rise every day, call number n steps back over all n - 1 earlier days. For n calls that is about n²/2 steps.
What each entry holds
What must an entry remember? Its price, to compare with new prices, and its span, the number of days it stands for. The span is what lets one removal add several days at once. In Java an entry can be a two-element int{price, span}ArrayDequepushpeekpop
When an entry comes off the stack
Which entries does a new price remove? Every entry on top whose price is less than or equal to today's. Equal prices must come off too, because the span counts days at or below today's price: with prices 5, 5, 5 the spans are 1, 2 and 3. The first entry with a higher price stops the removals and stays, because it can still stop later counts.
Java Solution
The class StockSpanner
- First, the field
is created empty with the object: anstack ofArrayDeque entries, each holdingint[] .{price, span} - Each call
starts withnext(price) , for today itself.span = 1 - A
loop reads the top entry withwhile . As long as the stack is not empty and the top price is at moststack.peek() , it pops that entry and adds its span toprice .span - When the loop stops, the stack is empty or its top price is higher than today's. Push the new entry
and return{price, span} .span
The mainStockSpannerspans
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringJoiner;
public class OnlineStockSpan {
static class StockSpanner {
private final Deque<int[]> stack = new ArrayDeque<>(); // {price, span}, prices falling
public int next(int price) {
int span = 1; // today counts
while (!stack.isEmpty() && stack.peek()[0] <= price) {
span += stack.pop()[1]; // take over the days that entry covered
}
stack.push(new int[] {price, span});
return span;
}
}
static String spans(int... prices) {
StockSpanner spanner = new StockSpanner();
StringJoiner in = new StringJoiner(", ");
StringJoiner out = new StringJoiner(", ");
for (int price : prices) {
in.add(String.valueOf(price));
out.add(String.valueOf(spanner.next(price)));
}
return in + " -> " + out;
}
public static void main(String[] args) {
System.out.println(spans(100, 80, 60, 70, 60, 75, 85));
System.out.println(spans(5, 5, 5));
System.out.println(spans(10, 20, 30, 40));
System.out.println(spans(40, 30, 20, 10));
System.out.println(spans(30, 10, 20, 10, 50));
}
}
Running it prints:
100, 80, 60, 70, 60, 75, 85 -> 1, 1, 1, 2, 1, 4, 6
5, 5, 5 -> 1, 2, 3
10, 20, 30, 40 -> 1, 2, 3, 4
40, 30, 20, 10 -> 1, 1, 1, 1
30, 10, 20, 10, 50 -> 1, 1, 2, 1, 5
The spans for the example prices, 1, 1, 1, 2, 1, 4, 6, match Example 1. The final 6, for 85, comes from popping price 75, span 4 and then price 80, span 1: 1 + 4 + 1. Only price 100 is left below it.
For 5, 5, 5 the spans are 1, 2, 3, because each 5 removes the 5 before it. With the strict check stack.peek()[0] < price5, 5, 5 -> 1, 1, 1
With rising prices, 10, 20, 30, 40, each call after the first pops the one entry on the stack, so the span grows by one per day without any walk back. With falling prices nothing is ever popped, and every span is 1. In the last line, 50 pops all three entries left on the stack, price 10, span 1, price 20, span 2 and price 30, span 1, for a span of 5.
The original implementation,
Complexity
A single call may pop many entries, but each price goes onto the stack once and comes off at most once.
- Time: O(1) per call on average over all calls, which is called amortized O(1). Over n calls there are n pushes and at most n pops, so the bodies of all the
loops together run at most n times. That holds even when one call, like 50 in the last line, pops several entries.while - Space: O(n) after n calls. The most is reached when prices keep falling: nothing is popped, and every day keeps its own two-number entry.
The span looks back for the previous higher price.