Leetcode 901: Online Stock Span

grid47
grid47
Exploring patterns and algorithms
Aug 8, 2024 5 min read

Design a system that processes daily stock price quotes and computes the price span for the current day. The price span for a day is defined as the maximum number of consecutive days (including today) where the price of the stock was less than or equal to today’s price.
Problem
Approach
Steps
Complexity
Input: The input consists of a sequence of operations where a 'next' operation receives the stock price of the current day.
Example: Input: ["StockSpanner", "next", "next", "next", "next", "next", "next"] [[], [120], [95], [100], [90], [130], [125]]
Constraints:
• 1 <= price <= 100000
• At most 10000 calls to the 'next' function.
Output: For each 'next' operation, output the price span for the provided stock price.
Example: Output: [null, 1, 1, 2, 1, 5, 2]
Constraints:
• Output is an integer for each 'next' operation, except the initialization which outputs null.
Goal: Compute the price span efficiently using a stack-based approach.
Steps:
• 1. Maintain a stack of price-span pairs.
• 2. For each new price, pop elements from the stack if they are less than or equal to the current price.
• 3. Sum the spans of the popped elements and include today's span (1).
• 4. Push the current price and its computed span onto the stack.
• 5. Return the span for the current day.
Goal: Constraints ensure efficient processing and valid input ranges.
Steps:
• Prices are guaranteed to be positive integers.
• The number of operations is capped at 10^4.
Assumptions:
• The input price is always a valid integer within the given range.
• The operations will always follow the sequence provided in the example.
Input: Input: ["StockSpanner", "next", "next", "next", "next", "next", "next"] [[], [90], [85], [95], [85], [110], [105]]
Explanation: Output: [null, 1, 1, 3, 1, 5, 2] Explanation: The span for each price is computed as follows: 1. [90]: Span = 1 2. [85]: Span = 1 3. [95]: Span = 3 (90, 85, 95) 4. [85]: Span = 1 5. [110]: Span = 5 (90, 85, 95, 85, 110) 6. [105]: Span = 2 (110, 105)

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus