Stock Span Problem Using Stack
📖 Scenario: You are working as a stock analyst. You want to find out how many consecutive days before today the stock price was less than or equal to today's price. This helps in understanding the stock's performance trend.
🎯 Goal: Build a program that calculates the stock span for each day using a stack. The stock span is the number of consecutive days before the current day where the stock price was less than or equal to the current day's price.
📋 What You'll Learn
Create a list called
prices with the exact values: [100, 80, 60, 70, 60, 75, 85]Create an empty list called
span to store the span valuesUse a stack implemented as a list called
stack to help calculate spansUse a
for loop with variable i to iterate over the indices of pricesInside the loop, use a
while loop to pop from stack while the top of the stack points to a price less than or equal to prices[i]Calculate the span for each day and append it to
spanPrint the
span list at the end💡 Why This Matters
🌍 Real World
Stock analysts use the stock span problem to understand how long a stock price has been rising or stable, helping in making investment decisions.
💼 Career
This problem teaches stack usage, which is important in many software engineering tasks like parsing, undo operations, and managing function calls.
Progress0 / 4 steps