Online Stock Span

Introduction

 
In this article, we will sove the leetcode problem #901, Minimum Falling Path Sum. The problem statement goes like this: Construct 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]. And here is how it's called using C#,
  1. static void Main(string[] args)  
  2. {  
  3.     var stockSpanner = new StockSpanner();  
  4.     var prices = new int[] { 100, 80, 60, 70, 60, 75, 85 };  
  5.     var result = new List<int>();  
  6.     foreach (var price in prices)  
  7.         result.Add(stockSpanner.Next(price));  
  8.     //result = [ 1, 1, 1, 2, 1, 4, 6]  
  9. }  
Note that (for example) stockSpanner.Next(75) returned 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
 

Solution

 
The most naive approach to this problem is by using stacks to store all the prices and then finally comparing them with the last price. If the current price is more than the last stored price we switch them and push the stack. Here is the C# code for the approach,
  1. class StockSpanner  
  2. {  
  3.     Stack<int[]> Stack;  
  4.   
  5.     public StockSpanner()  
  6.     {  
  7.         Stack = new Stack<int[]>();  
  8.     }  
  9.     public int Next(int price)  
  10.     {  
  11.         int result = 1;  
  12.         while (Stack.Count != 0 && Stack.Peek()[0] <= price)  
  13.         {  
  14.             result += Stack.Pop()[1];  
  15.         }  
  16.         Stack.Push(new int[] { price, result });  
  17.         return result;  
  18.     }  
  19. }