📖 Scenario: You are helping a friend who wants to understand how to make money by buying and selling stocks. They have a list of stock prices for several days and want to find the best way to buy and sell to maximize profit.
🎯 Goal: Build a simple program that finds the maximum profit from buying and selling stocks once, then extend it to multiple transactions, and finally print the results.
📋 What You'll Learn
Create a vector called prices with exact values: 7, 1, 5, 3, 6, 4
Create an integer variable called maxProfitOnce initialized to 0
Write a loop to find the maximum profit from one buy and one sell
Print the value of maxProfitOnce
💡 Why This Matters
🌍 Real World
This project simulates a simple stock trading scenario where you want to maximize profit by choosing the best days to buy and sell stocks.
💼 Career
Understanding how to analyze sequences and optimize decisions is useful in finance, data analysis, and algorithm design roles.
Progress0 / 4 steps
1
Create the stock prices vector
Create a std::vector<int> called prices with these exact values: 7, 1, 5, 3, 6, 4
DSA C++
Hint
Use std::vector<int> prices = {7, 1, 5, 3, 6, 4}; to create the vector.
2
Initialize the max profit variable
Create an integer variable called maxProfitOnce and set it to 0
DSA C++
Hint
Use int maxProfitOnce = 0; to create the variable.
3
Calculate max profit for one transaction
Write a for loop with variable i from 1 to prices.size() that calculates the maximum profit from one buy and one sell. Use an integer variable minPrice initialized to prices[0] to track the lowest price so far. Update maxProfitOnce with the maximum of its current value and prices[i] - minPrice. Also update minPrice with the minimum of its current value and prices[i].
DSA C++
Hint
Use a loop from 1 to prices.size(), track minPrice, and update maxProfitOnce using std::max and std::min.
4
Print the maximum profit from one transaction
Write a std::cout statement to print the value of maxProfitOnce followed by a newline.
DSA C++
Hint
Use std::cout << maxProfitOnce << std::endl; to print the result.
Practice
(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem with only one transaction allowed?
easy
A. Sell before buying to maximize profit
B. Minimize the buying price regardless of selling price
C. Buy and sell on the same day to avoid loss
D. Maximize the difference between a later selling price and an earlier buying price
Solution
Step 1: Understand the problem constraints
The problem allows only one buy and one sell, so the goal is to find the maximum profit from one pair of days where buying day is before selling day.
Step 2: Identify the profit calculation
Profit = selling price - buying price. We want to maximize this difference with the buying day before selling day.
Final Answer:
Maximize the difference between a later selling price and an earlier buying price -> Option D
Quick Check:
Profit = sell price - buy price [OK]
Hint: Find max difference with buy day before sell day [OK]
Common Mistakes:
Ignoring the order of buy and sell days
Trying to minimize price without considering selling
Assuming multiple transactions allowed
2. Which of the following C++ code snippets correctly initializes a vector of stock prices for the Buy and Sell Stocks problem?
In C++, a vector of integers is initialized with curly braces and type specified: std::vector<int> prices = {values};
Step 2: Check each option
std::vector<int> prices = {7, 1, 5, 3, 6, 4}; uses correct syntax with std::vector<int> and curly braces. Options A, B, and D use incorrect syntax for vector initialization.
Hint: Use std::vector<int> and curly braces {} to initialize [OK]
Common Mistakes:
Using square brackets [] instead of curly braces {}
Omitting the type <int>
Using parentheses () instead of braces
3. What is the output of the following C++ code that finds the maximum profit with unlimited transactions allowed?
std::vector<int> prices = {7, 1, 5, 3, 6, 4};
int maxProfit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
std::cout << maxProfit << std::endl;
medium
A. 7
B. 5
C. 8
D. 6
Solution
Step 1: Understand the loop and profit calculation
The code adds profit for every day where price increases from previous day, summing all positive differences.
Step 2: Calculate profits day by day
Day 1 to 2: 1 - 7 = -6 (no profit) Day 2 to 3: 5 - 1 = 4 (add 4) Day 3 to 4: 3 - 5 = -2 (no profit) Day 4 to 5: 6 - 3 = 3 (add 3) Day 5 to 6: 4 - 6 = -2 (no profit) Total profit = 4 + 3 = 7
Final Answer:
7 -> Option A
Quick Check:
Sum of positive differences = 7 [OK]
Hint: Sum all positive price differences for unlimited transactions [OK]
Common Mistakes:
Adding negative differences as profit
Only considering one transaction
Miscounting indices in loop
4. Identify the bug in this C++ code snippet that tries to find the maximum profit with only one transaction allowed:
std::vector<int> prices = {7, 1, 5, 3, 6, 4};
int minPrice = INT_MAX;
int maxProfit = 0;
for (int i = 0; i < prices.size(); i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
std::cout << maxProfit << std::endl;
medium
A. No bug, code works correctly
B. minPrice should be initialized to 0
C. maxProfit should be initialized to INT_MIN
D. Loop should start from i = 1 instead of 0
Solution
Step 1: Analyze initialization and loop
minPrice is set to INT_MAX to find minimum price correctly. maxProfit starts at 0. Loop from 0 to end checks each price.
Step 2: Check logic correctness
For each price, update minPrice if current price is lower. Else, calculate profit and update maxProfit if higher. This correctly finds max profit with one transaction.
Final Answer:
No bug, code works correctly -> Option A
Quick Check:
Correct minPrice and maxProfit updates [OK]
Hint: Initialize minPrice to INT_MAX and loop from 0 [OK]
Common Mistakes:
Starting loop from 1 and missing first price
Initializing minPrice to 0 causing wrong min
Initializing maxProfit to INT_MIN causing negative profits
5. Given the prices {3, 3, 5, 0, 0, 3, 1, 4}, what is the maximum profit achievable with at most two transactions?
hard
A. 5
B. 7
C. 6
D. 8
Solution
Step 1: Understand two transactions limit
We can buy and sell at most twice. We must find two pairs of buy-sell days maximizing total profit without overlap.
Step 2: Calculate max profit with two transactions
First transaction: Buy at 3 (day 1), sell at 5 (day 3) profit = 2 Second transaction: Buy at 0 (day 4), sell at 4 (day 8) profit = 4 Total profit = 2 + 4 = 6
Final Answer:
6 -> Option C
Quick Check:
Sum of two best transactions = 6 [OK]
Hint: Split prices into two parts, sum max profits [OK]
Common Mistakes:
Counting overlapping transactions
Only considering one transaction
Misidentifying buy/sell days
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.