Intermediate Level

Implement the onlineStockSpanLast method that returns the latest stock span value from the price stream.

The input contains an array prices and its length size. Each value represents the stock price on one day.

Your task is to return the stock span for the last day. The span is the number of consecutive days ending on the last day where the stock price was less than or equal to the last day price.

For example, for [100,80,60,70,60,75,85], the last price is 85. The consecutive prices 80,60,70,60,75,85 are all less than or equal to 85, so the answer is 6.

Example 1
Input:
prices (int[]) = [100,80,60,70,60,75,85]
size (int) = 7
Return:
(int) 6
Example 2
Input:
prices (int[]) = [10,20,30]
size (int) = 3
Return:
(int) 3
Example 3
Input:
prices (int[]) = [30,20,10]
size (int) = 3
Return:
(int) 1

Use a stack of pairs where each pair stores a price and its span.

For every new price, start its span as 1. While the stack top has a price less than or equal to the current price, pop it and add its span to the current span. This combines all previous consecutive days covered by that price.

Push the current price with its computed span. After processing all prices, the last computed span is the required answer.

Pseudocode:

function onlineStockSpanLast(prices, size):
    stack = empty stack of pairs(price, span)
    lastSpan = 0
    for each price in prices:
        span = 1
        while stack is not empty and top(stack).price <= price:
            span = span + top(stack).span
            pop stack
        push (price, span) into stack
        lastSpan = span
    return lastSpan
Run your code to see the result.