Bird
0
0
DSA Cprogramming~30 mins

Stock Span Problem Using Stack in DSA C - Build from Scratch

Choose your learning style9 modes available
Stock Span Problem Using Stack
📖 Scenario: Imagine you are tracking the daily prices of a stock. You want to find out for each day how many consecutive days before it had a price less than or equal to that day's price. This helps investors understand the stock's recent performance trend.
🎯 Goal: Build a program that calculates the stock span for each day using a stack data structure.
📋 What You'll Learn
Create an array called prices with the exact values: 100, 80, 60, 70, 60, 75, 85
Create an integer variable called n and set it to the length of prices
Create an integer array called span of size n to store the span values
Use a stack implemented as an integer array called stack and an integer top to manage it
Calculate the stock span for each day using the stack
Print the span array values separated by spaces
💡 Why This Matters
🌍 Real World
Stock span calculation helps investors understand how many days a stock price has been rising or stable, which is useful for making buy or sell decisions.
💼 Career
Understanding stack data structures and their applications like the stock span problem is important for software developers working on financial software, trading platforms, and algorithmic problem solving.
Progress0 / 4 steps
1
Create the prices array and its size
Create an integer array called prices with these exact values: 100, 80, 60, 70, 60, 75, 85. Then create an integer variable called n and set it to 7.
DSA C
Hint

Use int prices[] = { ... }; to create the array and int n = 7; for the size.

2
Create the span array and stack variables
Create an integer array called span of size n. Also create an integer array called stack of size n and an integer variable called top initialized to -1.
DSA C
Hint

Use int span[7]; and int stack[7]; to create arrays and int top = -1; to start the stack empty.

3
Calculate the stock span using the stack
Write a for loop with variable i from 0 to n-1. Inside the loop, pop from the stack while top is not -1 and prices[stack[top]] is less than or equal to prices[i]. Then set span[i] to i + 1 if top is -1, else to i - stack[top]. Finally, push i onto the stack by incrementing top and setting stack[top] = i.
DSA C
Hint

Use a loop from 0 to n-1. Inside, pop from stack while top is not -1 and price at stack[top] is less or equal to current price. Then calculate span and push current index.

4
Print the span array
Use a for loop with variable i from 0 to n-1 to print each span[i] followed by a space.
DSA C
Hint

Use a loop to print each span value followed by a space using printf("%d ", span[i]);.