Algorithm


Problem Name: 901. Online Stock Span

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.

  • For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days.
  • Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days.

Implement the StockSpanner class:

  • StockSpanner() Initializes the object of the class.
  • int next(int price) Returns the span of the stock's price given that today's price is price.

 

Example 1:

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:

  • 1 <= price <= 105
  • At most 104 calls will be made to next.

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class StockSpanner {
    
    // Entry in stack is the current price and count of prices <= current price
    private final Stack<int[]> stack;
    
    public StockSpanner() {
        this.stack = new Stack < >();
    }
    
    public int next(int price) {
        int count = 1;
        while (!stack.isEmpty() && stack.peek()[0]  < = price) {
            count += stack.pop()[1];
        }
        stack.push(new int[]{price, count});
        return count;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] [[], [100], [80], [60], [70], [60], [75], [85]]

Output

x
+
cmd
[null, 1, 1, 1, 2, 1, 4, 6]

#2 Code Example with Javascript Programming

Code - Javascript Programming


const StockSpanner = function() {
  this.values = []
}

StockSpanner.prototype.next = function(price) {
  let count = 1
  while (
    this.values.length > 0 &&
    this.values[this.values.length - 1][0] <= price
  ) {
    count += this.values.pop()[1]
  }
  this.values.push([price, count])
  return count
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] [[], [100], [80], [60], [70], [60], [75], [85]]

Output

x
+
cmd
[null, 1, 1, 1, 2, 1, 4, 6]

#3 Code Example with Python Programming

Code - Python Programming


class StockSpanner:

    def __init__(self):
        self.arr = []  
        self.res = []

    def next(self, price):
        """
        :type price: int
        :rtype: int
        """
        if self.arr and self.arr[-1] > price: self.res.append(1)
        else:
            i = len(self.arr) - 1
            while i >= 0:
                if self.arr[i] <= price and self.res[i]:
                    i -= self.res[i]
                else: break
            self.res.append(len(self.arr) - i)
        self.arr.append(price)
        return self.res[-1]
Copy The Code & Try With Live Editor

Input

x
+
cmd
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] [[], [100], [80], [60], [70], [60], [75], [85]]

Output

x
+
cmd
[null, 1, 1, 1, 2, 1, 4, 6]

#4 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0901_OnlineStockSpan
    {
        private Stack < int[]> stack = new Stack<int[]>();

        public _0901_OnlineStockSpan()
        {
        }

        public int Next(int price)
        {
            int span = 1;
            while (stack.Count > 0 && stack.Peek()[0]  < = price)
                span += stack.Pop()[1];

            stack.Push(new int[] { price, span });
            return span;
        }
    }

}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"] [[], [100], [80], [60], [70], [60], [75], [85]]

Output

x
+
cmd
[null, 1, 1, 1, 2, 1, 4, 6]
Advertisements

Demonstration


Previous
#900 Leetcode RLE Iterator Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#902 Leetcode Numbers At Most N Given Digit Set Solution in C, C++, Java, JavaScript, Python, C# Leetcode