Bird
Raised Fist0
DSA Javascriptprogramming

Buy and Sell Stocks All Variants in DSA Javascript

Choose your learning style10 modes available
Mental Model
We want to find the best times to buy and sell stocks to maximize profit by looking at price changes over days.
Analogy: Imagine you buy fruits at a low price one day and sell them later at a higher price to earn money, but you can only hold one fruit at a time or multiple depending on the rules.
Day:    0    1    2    3    4    5
Price: 100 -> 180 -> 260 -> 310 -> 40 -> 535
Buy/Sell points show where to buy low and sell high.
Dry Run Walkthrough
Input: prices: [100, 180, 260, 310, 40, 535], max 2 transactions allowed
Goal: Maximize profit by buying and selling stocks at most twice
Step 1: Find first buy at day 0 (price 100)
Buy at 100, profit = 0
Why: Start with lowest price to maximize profit
Step 2: Sell first stock at day 3 (price 310)
Profit from first transaction = 310 - 100 = 210
Why: Sell at highest price before price drops
Step 3: Buy second stock at day 4 (price 40)
Hold second stock bought at 40
Why: Price dropped, good opportunity to buy again
Step 4: Sell second stock at day 5 (price 535)
Profit from second transaction = 535 - 40 = 495
Why: Sell at highest price to maximize second profit
Result:
Total profit = 210 + 495 = 705
Annotated Code
DSA Javascript
class StockTrader {
  // Calculate max profit with at most k transactions
  maxProfit(prices, k) {
    if (prices.length === 0) return 0;
    const n = prices.length;
    if (k === 0) return 0;
    if (k >= n / 2) {
      // If k is large, treat as infinite transactions
      let profit = 0;
      for (let i = 1; i < n; i++) {
        if (prices[i] > prices[i - 1]) {
          profit += prices[i] - prices[i - 1];
        }
      }
      return profit;
    }
    const dp = Array.from({ length: k + 1 }, () => Array(n).fill(0));
    for (let t = 1; t <= k; t++) {
      let maxDiff = -prices[0];
      for (let d = 1; d < n; d++) {
        dp[t][d] = Math.max(dp[t][d - 1], prices[d] + maxDiff);
        maxDiff = Math.max(maxDiff, dp[t - 1][d] - prices[d]);
      }
    }
    return dp[k][n - 1];
  }
}

// Driver code
const trader = new StockTrader();
const prices = [100, 180, 260, 310, 40, 535];
const maxTransactions = 2;
const result = trader.maxProfit(prices, maxTransactions);
console.log(result);
if (k >= n / 2) { ... }
Handle case where transactions are unlimited by summing all positive gains
const dp = Array.from({ length: k + 1 }, () => Array(n).fill(0));
Create DP table for profits with up to k transactions and n days
for (let t = 1; t <= k; t++) {
Iterate over number of transactions
let maxDiff = -prices[0];
Track max difference of profit from previous transaction minus price
dp[t][d] = Math.max(dp[t][d - 1], prices[d] + maxDiff);
Choose max between no transaction today or selling today with best previous buy
maxDiff = Math.max(maxDiff, dp[t - 1][d] - prices[d]);
Update maxDiff for next day to consider buying at day d
OutputSuccess
705
Complexity Analysis
Time: O(k * n) because we fill a DP table with k transactions and n days
Space: O(k * n) for the DP table storing profits for each transaction and day
vs Alternative: Naive approach tries all buy/sell pairs with O(n^2) per transaction, which is slower
Edge Cases
Empty prices array
Returns 0 profit because no transactions possible
DSA Javascript
if (prices.length === 0) return 0;
k is zero (no transactions allowed)
Returns 0 profit because no buys or sells allowed
DSA Javascript
if (k === 0) return 0;
Prices always decreasing
Returns 0 profit because no profitable transactions
DSA Javascript
dp[t][d] = Math.max(dp[t][d - 1], prices[d] + maxDiff);
When to Use This Pattern
When asked to maximize stock profit with limited transactions, use dynamic programming with transaction count and day indices to track best profits.
Common Mistakes
Mistake: Trying to buy and sell on the same day or ignoring transaction limits
Fix: Use DP to track profits per transaction and day, ensuring buy before sell and respecting max transactions
Mistake: Not handling the case when transactions are unlimited efficiently
Fix: Add a shortcut to sum all positive price differences when k >= n/2
Summary
Calculates maximum profit from stock prices with a limit on buy-sell transactions.
Use when you need to find best profit with at most k transactions over multiple days.
Track profits with dynamic programming by storing best results per transaction count and day.

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