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 in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.

Implement the StockSpanner class:

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:

Contents

In this approach, we are going to build a monotonically decreasing stack, meaning that elements in the stack should be in a decreasing order, when we see a number higher than the top of the stack, then we delete elements from stack to ensure that the stack is still monotonically decreasing order.

Let's understand this with an example prices = [100, 80, 60, 70, 60, 75, 85]

Implementation steps:
import java.util.Stack; public class StockSpanner { final Stack<int[]> priceSpanPair; // each array will have two values -> price, span public StockSpanner() { priceSpanPair = new Stack<>(); } public int next(int price) { int span = 1; while(!priceSpanPair.isEmpty() && priceSpanPair.peek()[0] <= price) { span += priceSpanPair.peek()[1]; priceSpanPair.pop(); } priceSpanPair.push(new int[]{price, span}); return span; } public static void main(String[] args) { StockSpanner stockSpanner = new StockSpanner(); System.out.println(stockSpanner.next(100)); System.out.println(stockSpanner.next(80)); System.out.println(stockSpanner.next(60)); System.out.println(stockSpanner.next(70)); System.out.println(stockSpanner.next(60)); System.out.println(stockSpanner.next(75)); System.out.println(stockSpanner.next(85)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the number of times next method is called.
Space complexity: O(n) for the stack.

Above implementations source code can be found at GitHub link for Java code