0
0
DSA Cprogramming~30 mins

Buy and Sell Stocks All Variants in DSA C - Build from Scratch

Choose your learning style9 modes available
Buy and Sell Stocks All Variants
📖 Scenario: You are working on a simple stock trading app. You want to help users find the best way to buy and sell stocks to maximize their profit.The stock prices for a few days are given. You will write code to find the best profit for different trading rules.
🎯 Goal: Build a program that calculates the maximum profit from stock prices with different buying and selling rules.
📋 What You'll Learn
Create an array called prices with exact values: 7, 1, 5, 3, 6, 4
Create an integer variable called n that stores the size of the prices array
Write a function maxProfitSingleTransaction that returns the max profit from one buy and one sell
Write a function maxProfitMultipleTransactions that returns max profit from multiple buys and sells
Print the results of both functions
💡 Why This Matters
🌍 Real World
Stock trading apps and financial analysis tools use these algorithms to help users make smart buy and sell decisions.
💼 Career
Understanding these algorithms is important for software engineers working in finance, trading platforms, and data analysis roles.
Progress0 / 4 steps
1
Create the stock prices array
Create an integer array called prices with these exact values: 7, 1, 5, 3, 6, 4. Also create an integer variable called n that stores the size of the prices array.
DSA C
Hint

Use int prices[] = {7, 1, 5, 3, 6, 4}; to create the array and int n = sizeof(prices) / sizeof(prices[0]); to get its size.

2
Add function for max profit with single transaction
Add a function called maxProfitSingleTransaction that takes prices array and n as parameters and returns the maximum profit from one buy and one sell. Use variables minPrice and maxProfit inside the function.
DSA C
Hint

Use a for loop starting from 1 to n-1. Track the minimum price seen so far and update max profit if current price minus min price is higher.

3
Add function for max profit with multiple transactions
Add a function called maxProfitMultipleTransactions that takes prices array and n as parameters and returns the maximum profit from multiple buy and sell transactions. Use a for loop to add all positive differences between consecutive days.
DSA C
Hint

Loop from 1 to n-1 and add the difference to maxProfit whenever today's price is higher than yesterday's.

4
Print the results of both functions
In main, call maxProfitSingleTransaction(prices, n) and maxProfitMultipleTransactions(prices, n). Print the results with these exact messages:
"Max profit with single transaction: %d\n" and "Max profit with multiple transactions: %d\n".
DSA C
Hint

Call both functions with prices and n. Use printf to print the results with the exact messages.