Bird
Raised Fist0
DSA Javascriptprogramming~15 mins

Buy and Sell Stocks All Variants in DSA Javascript - Deep Dive

Choose your learning style10 modes available
Overview - Buy and Sell Stocks All Variants
What is it?
Buying and selling stocks problems ask how to maximize profit from stock prices given certain rules. You have a list of prices, each representing the stock price on a day. The goal is to decide when to buy and sell to get the most money. Different variants add rules like limits on transactions or cooldown days.
Why it matters
These problems teach how to make optimal decisions over time with constraints, a skill useful in finance and many real-world planning tasks. Without understanding these patterns, you might miss the best way to maximize gains or minimize losses in changing conditions.
Where it fits
You should know arrays and basic loops before this. After this, you can learn dynamic programming and greedy algorithms more deeply, as these problems often use those techniques.
Mental Model
Core Idea
Maximize profit by choosing the best days to buy low and sell high under given rules.
Think of it like...
It's like buying fruits at a market when prices are low and selling them later when prices rise, but sometimes you can only carry a few fruits or must wait a day before selling again.
Day:    1    2    3    4    5
Price:  7    1    5    3    6
Buy on day 2 (price 1), sell on day 3 (price 5) -> profit 4
Buy on day 4 (price 3), sell on day 5 (price 6) -> profit 3
Total profit = 7
Build-Up - 7 Steps
1
FoundationSingle Transaction Maximum Profit
πŸ€”
Concept: Find the best single buy and sell day to maximize profit.
Given an array of prices, track the lowest price seen so far and calculate profit if sold today. Update max profit if current profit is higher. Only one buy and one sell allowed.
Result
For prices [7,1,5,3,6,4], max profit is 5 (buy at 1, sell at 6).
Understanding how to track minimum price and calculate profit on the fly is the base for all stock problems.
2
FoundationMultiple Transactions Unlimited
πŸ€”
Concept: Allow buying and selling multiple times to maximize total profit.
You can buy and sell as many times as you want, but you must sell before buying again. Add all positive differences between consecutive days.
Result
For prices [7,1,5,3,6,4], total profit is 7 (buy at 1 sell at 5, buy at 3 sell at 6).
Summing positive price jumps captures all profitable trades without complex tracking.
3
IntermediateAt Most Two Transactions
πŸ€”Before reading on: do you think splitting the array into two parts and summing max profits works? Commit to yes or no.
Concept: Limit to at most two buy-sell transactions to maximize profit.
Use two passes: forward pass to find max profit up to each day, backward pass to find max profit from each day to end. Combine to find max total profit with two transactions.
Result
For prices [3,3,5,0,0,3,1,4], max profit is 6 (buy at 0 sell at 3, buy at 1 sell at 4).
Breaking problem into two parts and combining results is a powerful dynamic programming technique.
4
IntermediateK Transactions Limit
πŸ€”Before reading on: do you think a simple greedy approach works for k transactions? Commit to yes or no.
Concept: Generalize to at most k transactions using dynamic programming.
Use a DP table where dp[t][d] is max profit with t transactions by day d. Update by comparing no transaction today or selling today after buying on a previous day.
Result
For prices [2,4,1] and k=2, max profit is 2 (buy at 2 sell at 4).
Dynamic programming handles complex constraints by breaking problem into smaller subproblems.
5
IntermediateCooldown Period After Selling
πŸ€”Before reading on: do you think you can buy immediately after selling? Commit to yes or no.
Concept: Add a cooldown day after selling before you can buy again.
Track three states: holding stock, not holding and in cooldown, and not holding and ready to buy. Update states each day based on previous states.
Result
For prices [1,2,3,0,2], max profit is 3 (buy day 1 sell day 3 cooldown day 4 buy day 5 sell day 6).
Modeling states explicitly helps handle timing constraints in decisions.
6
AdvancedTransaction Fee Per Trade
πŸ€”Before reading on: do you think fees affect when to buy or sell? Commit to yes or no.
Concept: Subtract a fee from profit each time you sell.
Modify the state transitions to subtract fee when selling. Track holding and not holding states similarly to cooldown problem.
Result
For prices [1,3,2,8,4,9] and fee=2, max profit is 8.
Incorporating fees changes optimal trade timing, requiring careful state updates.
7
ExpertOptimizing Space and Time Complexity
πŸ€”Before reading on: do you think storing full DP tables is always necessary? Commit to yes or no.
Concept: Use variables to track only needed states to reduce memory and speed up.
Instead of full DP arrays, keep track of best buy and sell profits for each transaction count using rolling variables. This reduces space from O(k*n) to O(k).
Result
For large inputs, this approach runs faster and uses less memory without changing results.
Recognizing which data is essential allows efficient algorithms suitable for real-world large data.
Under the Hood
These problems use dynamic programming to remember past decisions and their profits. States represent whether you hold stock or not, how many transactions done, and cooldown or fees. Transitions update states day by day based on prices and rules. This avoids recomputing all possibilities.
Why designed this way?
Stock trading problems model real financial constraints like limited trades, cooldowns, and fees. Dynamic programming fits because it breaks complex decisions into manageable steps, balancing past and future choices efficiently.
Day 1    Day 2    Day 3    ...    Day n
β”Œβ”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”
β”‚Stateβ”‚-> β”‚Stateβ”‚-> β”‚Stateβ”‚  ... ->  β”‚Stateβ”‚
β””β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”˜
Each state tracks holding, transactions, cooldown
Transitions update profit based on price and rules
Myth Busters - 4 Common Misconceptions
Quick: Can you always buy and sell on the same day for max profit? Commit yes or no.
Common Belief:You can buy and sell on the same day to maximize profit.
Tap to reveal reality
Reality:You must buy before you sell, so buying and selling on the same day is not allowed.
Why it matters:Ignoring this leads to incorrect profit calculations and invalid solutions.
Quick: Does summing all positive price differences always give max profit with transaction limits? Commit yes or no.
Common Belief:Adding all positive price jumps works even with transaction limits.
Tap to reveal reality
Reality:This only works when unlimited transactions are allowed; limits require dynamic programming.
Why it matters:Using greedy sums with limits causes wrong answers and missed optimal profits.
Quick: Does adding cooldown days always reduce profit? Commit yes or no.
Common Belief:Cooldown days always reduce maximum profit.
Tap to reveal reality
Reality:Cooldowns restrict trading frequency but can sometimes force better timing, not always reducing profit drastically.
Why it matters:Assuming cooldowns only hurt can mislead strategy design and algorithm choices.
Quick: Is storing full DP tables always necessary for k transactions? Commit yes or no.
Common Belief:You must store all DP states for every day and transaction count.
Tap to reveal reality
Reality:You can optimize space by storing only essential states, reducing memory use.
Why it matters:Not optimizing leads to inefficient solutions unsuitable for large inputs.
Expert Zone
1
Tracking states separately for holding and not holding stock simplifies handling cooldowns and fees.
2
The order of updating states matters; updating sell states before buy states prevents using today's price twice.
3
For large k, the problem reduces to unlimited transactions, allowing simpler greedy solutions.
When NOT to use
Avoid these algorithms when stock prices are not given as arrays or when real-time streaming data requires online algorithms. For very large k, use greedy approaches instead of DP. For complex market models with multiple stocks or stochastic prices, use advanced financial models.
Production Patterns
In real trading systems, these algorithms help design automated trading bots with constraints. They also appear in coding interviews to test dynamic programming skills. Variants are used in portfolio optimization and risk management.
Connections
Dynamic Programming
Builds-on
Understanding stock problems deepens grasp of dynamic programming state management and optimization.
Greedy Algorithms
Opposite approach
Comparing greedy and DP solutions here clarifies when greedy works and when it fails.
Project Management Scheduling
Similar pattern
Deciding when to buy/sell under constraints is like scheduling tasks with cooldowns and limited resources.
Common Pitfalls
#1Trying to buy and sell on the same day.
Wrong approach:for(let i=0; i
Correct approach:Track min price before day i and calculate profit only if sell day > buy day.
Root cause:Misunderstanding that buy must happen before sell.
#2Summing all positive differences even with transaction limits.
Wrong approach:let profit = 0; for(let i=1; iprices[i-1]) profit += prices[i]-prices[i-1]; } // wrong for limited k
Correct approach:Use DP to track profits with transaction count constraints.
Root cause:Confusing unlimited and limited transaction rules.
#3Ignoring cooldown days and buying immediately after selling.
Wrong approach:Buy on day i+1 right after selling on day i without cooldown check.
Correct approach:Model cooldown state and skip buying on cooldown days.
Root cause:Not modeling problem constraints explicitly.
Key Takeaways
Maximizing stock profit involves choosing buy and sell days carefully under given rules.
Dynamic programming helps solve complex constraints like transaction limits, cooldowns, and fees by tracking states over time.
Greedy solutions work only when transactions are unlimited and no extra constraints exist.
Optimizing space and time complexity is crucial for handling large inputs efficiently.
Understanding these variants builds strong problem-solving skills applicable beyond stock trading.

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