Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Buy and Sell Stocks All Variants in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Buy and Sell Stocks All Variants
Start: Prices Array
↓
Choose Variant
↓
One Transaction
↓
Track Min Price
↓
Calculate Max Profit
↓
Result
The flow starts with the prices array, then chooses the variant of the problem, and follows the specific logic to calculate max profit.
Execution Sample
DSA Javascript
const prices = [7,1,5,3,6,4];
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
  minPrice = Math.min(minPrice, price);
  maxProfit = Math.max(maxProfit, price - minPrice);
}
console.log(maxProfit);
This code finds the max profit from one buy-sell transaction by tracking the minimum price and max profit.
Execution Table
StepCurrent PriceMin PricePrice - Min PriceMax ProfitVisual State
17700[7] (minPrice=7, maxProfit=0)
21100[7,1] (minPrice=1, maxProfit=0)
35144[7,1,5] (minPrice=1, maxProfit=4)
43124[7,1,5,3] (minPrice=1, maxProfit=4)
56155[7,1,5,3,6] (minPrice=1, maxProfit=5)
64135[7,1,5,3,6,4] (minPrice=1, maxProfit=5)
Exit----End of prices array, maxProfit=5
💡 Reached end of prices array, no more prices to process.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6Final
minPriceInfinity7111111
maxProfit00044555
price-715364-
Key Moments - 3 Insights
Why do we update minPrice before calculating maxProfit?
Because we want to buy at the lowest price seen so far before selling. Updating minPrice first ensures we consider the best buying price before checking profit (see steps 2 and 3 in execution_table).
Why does maxProfit not update when price is less than minPrice?
When price is less than minPrice, it means we found a new lower buying price, so maxProfit stays the same because selling now would not be profitable (see step 2).
Why do we subtract minPrice from current price to get profit?
Profit is the difference between selling price and buying price. minPrice represents the best buying price so far, so price - minPrice gives the profit if sold now (see column 'Price - Min Price').
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is maxProfit after processing price 5 (step 3)?
A4
B5
C0
D1
💡 Hint
Check the 'Max Profit' column at step 3 in execution_table.
At which step does minPrice update to 1?
AStep 3
BStep 1
CStep 2
DStep 5
💡 Hint
Look at the 'Min Price' column in execution_table and variable_tracker.
If prices were strictly decreasing, what would maxProfit be at the end?
APositive number
BZero
CNegative number
DInfinity
💡 Hint
Profit cannot be negative; maxProfit only updates if price - minPrice is positive.
Concept Snapshot
Buy and Sell Stocks Variants:
- Track min price to buy low
- Calculate profit as current price - min price
- Update max profit if current profit is higher
- Variants include one transaction, multiple transactions, cooldown
- Use loops and comparisons to update variables
- Result is max profit achievable
Full Transcript
This visualization shows how to find the maximum profit from buying and selling stocks in different variants. We start with an array of prices. For the one transaction variant, we track the minimum price seen so far and calculate the profit if we sell at the current price. We update the maximum profit if this profit is higher. The execution table shows each step with current price, min price, profit, and max profit. The variable tracker shows how minPrice and maxProfit change after each price. Key moments clarify why minPrice updates before maxProfit and why profit is calculated as price minus minPrice. The quiz tests understanding of these steps. This approach can be extended to other variants like multiple transactions or cooldown periods.

Practice

(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem variants?
easy
A. Maximize the profit by choosing the best days to buy and sell stocks
B. Minimize the number of transactions regardless of profit
C. Find the day with the highest stock price only
D. Calculate the average stock price over all days

Solution

  1. Step 1: Understand the problem goal

    The problem asks to find the best days to buy and sell stocks to get the highest profit.
  2. Step 2: Identify the objective

    Maximizing profit means buying low and selling high at the right times.
  3. Final Answer:

    Maximize the profit by choosing the best days to buy and sell stocks -> Option A
  4. Quick Check:

    Goal = Maximize profit [OK]
Hint: Focus on profit maximization, not just prices or counts [OK]
Common Mistakes:
  • Thinking the goal is to minimize transactions
  • Only looking for highest price day
  • Calculating average price instead of profit
2. Which of the following is the correct syntax to initialize a variable maxProfit to 0 in JavaScript?
easy
A. var maxProfit == 0;
B. let maxProfit = 0;
C. maxProfit := 0;
D. int maxProfit = 0;

Solution

  1. Step 1: Identify correct JavaScript variable declaration

    JavaScript uses let or const for variable declaration and single equals = for assignment.
  2. Step 2: Check each option

    let maxProfit = 0; uses let maxProfit = 0; which is correct syntax.
  3. Final Answer:

    let maxProfit = 0; -> Option B
  4. Quick Check:

    Variable declaration with let and = assignment [OK]
Hint: Use let or const with single = for assignment in JavaScript [OK]
Common Mistakes:
  • Using double equals == for assignment
  • Using := which is not JavaScript syntax
  • Using int which is not a JavaScript keyword
3. What will be the output of the following code snippet?
const prices = [7,1,5,3,6,4];
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
  if (price < minPrice) minPrice = price;
  else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
console.log(maxProfit);
medium
A. 7
B. 6
C. 4
D. 5

Solution

  1. Step 1: Track minimum price and maximum profit

    Iterate prices: minPrice updates to 7, then 1; maxProfit updates when price - minPrice is larger.
  2. Step 2: Calculate maxProfit step-by-step

    Prices: 7 (minPrice=7), 1 (minPrice=1), 5 (profit=4), 3 (profit=2), 6 (profit=5), 4 (profit=3). Max profit is 5.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Max profit = 5 [OK]
Hint: Track min price and update max profit on the fly [OK]
Common Mistakes:
  • Confusing minPrice update logic
  • Calculating profit incorrectly
  • Using max price instead of max profit
4. The following code is intended to find the maximum profit from one transaction but has a bug. What is the bug?
function maxProfit(prices) {
  let minPrice = 0;
  let maxProfit = 0;
  for (let price of prices) {
    if (price < minPrice) minPrice = price;
    else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
  }
  return maxProfit;
}
medium
A. minPrice should be initialized to Infinity, not 0
B. maxProfit should be initialized to -Infinity
C. The for loop should use index instead of for-of
D. The return statement is missing

Solution

  1. Step 1: Check initialization of minPrice

    minPrice is set to 0, but prices can be greater than 0, so minPrice never updates correctly if all prices are above 0.
  2. Step 2: Correct initialization

    minPrice should start at Infinity to ensure it updates to the first price correctly.
  3. Final Answer:

    minPrice should be initialized to Infinity, not 0 -> Option A
  4. Quick Check:

    minPrice init = Infinity [OK]
Hint: Initialize minPrice to Infinity to track minimum correctly [OK]
Common Mistakes:
  • Initializing minPrice to 0 causes wrong min tracking
  • Thinking maxProfit needs -Infinity initialization
  • Confusing loop types for this problem
5. Given the prices array [3,3,5,0,0,3,1,4], what is the maximum profit with at most two transactions?
hard
A. 5
B. 6
C. 7
D. 4

Solution

  1. Step 1: Understand two transactions limit

    We can buy and sell twice to maximize profit, but transactions cannot overlap.
  2. Step 2: Calculate profits for two transactions

    First transaction: buy at 3, sell at 5 (profit 2). Second transaction: buy at 0, sell at 4 (profit 5). Total profit = 2 + 5 = 7.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    Two transactions profit = 7 [OK]
Hint: Split array, find max profit in two parts, sum them [OK]
Common Mistakes:
  • Trying to do more than two transactions
  • Adding profits from overlapping transactions
  • Missing the best buy/sell days for each transaction
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard