Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Buy and Sell Stocks All Variants in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Stock Trading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this code for max profit with one transaction?
Given the prices array, what is the maximum profit from one buy and one sell?
DSA Typescript
function maxProfitOneTransaction(prices: number[]): number {
  let minPrice = Infinity;
  let maxProfit = 0;
  for (const price of prices) {
    if (price < minPrice) {
      minPrice = price;
    } else if (price - minPrice > maxProfit) {
      maxProfit = price - minPrice;
    }
  }
  return maxProfit;
}

const prices = [7,1,5,3,6,4];
console.log(maxProfitOneTransaction(prices));
A3
B5
C4
D6
Attempts:
2 left
💡 Hint
Track the lowest price and calculate profit by subtracting it from current price.
❓ Predict Output
intermediate
2:00remaining
What is the output of max profit with unlimited transactions?
Calculate the maximum profit if you can buy and sell stocks multiple times (unlimited transactions).
DSA Typescript
function maxProfitUnlimitedTransactions(prices: number[]): number {
  let profit = 0;
  for (let i = 1; i < prices.length; i++) {
    if (prices[i] > prices[i - 1]) {
      profit += prices[i] - prices[i - 1];
    }
  }
  return profit;
}

const prices = [7,1,5,3,6,4];
console.log(maxProfitUnlimitedTransactions(prices));
A7
B8
C5
D6
Attempts:
2 left
💡 Hint
Add all positive differences between consecutive days.
❓ Predict Output
advanced
2:30remaining
What is the output of max profit with at most two transactions?
Find the maximum profit with at most two buy-sell transactions.
DSA Typescript
function maxProfitTwoTransactions(prices: number[]): number {
  const n = prices.length;
  if (n === 0) return 0;
  const leftProfits = new Array(n).fill(0);
  let minPrice = prices[0];
  for (let i = 1; i < n; i++) {
    minPrice = Math.min(minPrice, prices[i]);
    leftProfits[i] = Math.max(leftProfits[i - 1], prices[i] - minPrice);
  }
  const rightProfits = new Array(n + 1).fill(0);
  let maxPrice = prices[n - 1];
  for (let i = n - 2; i >= 0; i--) {
    maxPrice = Math.max(maxPrice, prices[i]);
    rightProfits[i] = Math.max(rightProfits[i + 1], maxPrice - prices[i]);
  }
  let maxProfit = 0;
  for (let i = 0; i < n; i++) {
    maxProfit = Math.max(maxProfit, leftProfits[i] + rightProfits[i + 1]);
  }
  return maxProfit;
}

const prices = [3,3,5,0,0,3,1,4];
console.log(maxProfitTwoTransactions(prices));
A7
B4
C5
D6
Attempts:
2 left
💡 Hint
Use two passes: left to right and right to left to track profits.
❓ Predict Output
advanced
2:30remaining
What is the output of max profit with cooldown period?
Calculate max profit if after selling stock you must wait one day before buying again.
DSA Typescript
function maxProfitWithCooldown(prices: number[]): number {
  const n = prices.length;
  if (n <= 1) return 0;
  let sold = 0, hold = -prices[0], rest = 0;
  for (let i = 1; i < n; i++) {
    const prevSold = sold;
    sold = hold + prices[i];
    hold = Math.max(hold, rest - prices[i]);
    rest = Math.max(rest, prevSold);
  }
  return Math.max(sold, rest);
}

const prices = [1,2,3,0,2];
console.log(maxProfitWithCooldown(prices));
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Track three states: sold, hold, and rest to handle cooldown.
❓ Predict Output
expert
3:00remaining
What is the output of max profit with transaction fee?
Calculate max profit if each transaction costs a fee.
DSA Typescript
function maxProfitWithFee(prices: number[], fee: number): number {
  const n = prices.length;
  if (n === 0) return 0;
  let cash = 0;
  let hold = -prices[0];
  for (let i = 1; i < n; i++) {
    cash = Math.max(cash, hold + prices[i] - fee);
    hold = Math.max(hold, cash - prices[i]);
  }
  return cash;
}

const prices = [1,3,2,8,4,9];
const fee = 2;
console.log(maxProfitWithFee(prices, fee));
A5
B7
C6
D8
Attempts:
2 left
💡 Hint
Track cash and hold states, subtract fee when selling.

Practice

(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem with only one transaction allowed?
easy
A. Maximize the difference between a later selling price and an earlier buying price
B. Minimize the number of transactions
C. Find the lowest price in the array
D. Calculate the average stock price

Solution

  1. Step 1: Understand the problem goal

    The problem asks to find the maximum profit by buying and selling once, so we want the biggest positive difference between a sell price after a buy price.
  2. Step 2: Identify the correct approach

    Maximizing the difference between a later selling price and an earlier buying price directly solves the problem.
  3. Final Answer:

    Maximize the difference between a later selling price and an earlier buying price -> Option A
  4. Quick Check:

    Goal = Maximize profit from one buy and one sell [OK]
Hint: Look for max difference with sell after buy [OK]
Common Mistakes:
  • Thinking to minimize transactions instead of maximizing profit
  • Confusing lowest price with max profit
  • Ignoring the order of buy before sell
2. Which of the following TypeScript function signatures correctly represents a function to find max profit from multiple stock transactions?
easy
A. function maxProfit(prices: number[]): number
B. function maxProfit(prices: string): number[]
C. function maxProfit(prices: number): string
D. function maxProfit(prices: any): void

Solution

  1. Step 1: Analyze the input and output types

    The input should be an array of numbers representing prices, so prices: number[]. The output is the maximum profit, a number.
  2. Step 2: Match the correct function signature

    function maxProfit(prices: number[]): number matches input as number array and output as number, which is correct.
  3. Final Answer:

    function maxProfit(prices: number[]): number -> Option A
  4. Quick Check:

    Input array, output number [OK]
Hint: Input array of numbers, output single number [OK]
Common Mistakes:
  • Using string type for prices
  • Returning array instead of number
  • Using void return type
3. What is the output of the following TypeScript code for max profit with unlimited transactions?
function maxProfit(prices: number[]): number {
  let profit = 0;
  for (let i = 1; i < prices.length; i++) {
    if (prices[i] > prices[i - 1]) {
      profit += prices[i] - prices[i - 1];
    }
  }
  return profit;
}

console.log(maxProfit([7,1,5,3,6,4]));
medium
A. 5
B. 7
C. 8
D. 6

Solution

  1. Step 1: Trace the loop and calculate profit increments

    Prices: [7,1,5,3,6,4] - i=1: 1 > 7? No, profit=0 - i=2: 5 > 1? Yes, profit += 5-1=4 - i=3: 3 > 5? No, profit=4 - i=4: 6 > 3? Yes, profit += 6-3=3, total=7 - i=5: 4 > 6? No, profit=7
  2. Step 2: Return total profit

    Total profit after loop is 7.
  3. Final Answer:

    7 -> Option B
  4. Quick Check:

    Sum of positive diffs = 7 [OK]
Hint: Add all positive price differences [OK]
Common Mistakes:
  • Adding negative differences
  • Only considering one transaction
  • Misreading array indices
4. Identify the bug in this TypeScript code for max profit with one transaction:
function maxProfit(prices: number[]): number {
  let minPrice = prices[0];
  let maxProfit = 0;
  for (let i = 1; i <= prices.length; i++) {
    if (prices[i] < minPrice) {
      minPrice = prices[i];
    } else if (prices[i] - minPrice > maxProfit) {
      maxProfit = prices[i] - minPrice;
    }
  }
  return maxProfit;
}
medium
A. prices array should be sorted first
B. minPrice should be initialized to 0
C. maxProfit should start at -Infinity
D. Loop condition should be < instead of <=

Solution

  1. Step 1: Check loop boundary

    The loop runs with i from 1 to prices.length inclusive, but array indices go from 0 to prices.length - 1. Using <= causes out-of-bounds access at prices[prices.length].
  2. Step 2: Correct the loop condition

    Change loop condition to i < prices.length to avoid accessing undefined elements.
  3. Final Answer:

    Loop condition should be < instead of <= -> Option D
  4. Quick Check:

    Array index out-of-bounds fixed by < condition [OK]
Hint: Use < for array loops, not <= [OK]
Common Mistakes:
  • Using <= causing runtime errors
  • Initializing minPrice incorrectly
  • Sorting prices unnecessarily
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 at most twice. We want to split the array into two parts and maximize profit from each.
  2. Step 2: Calculate max profit for each split

    Best first transaction: buy at 3, sell at 5 = 2 profit Best second transaction: buy at 0, sell at 4 = 4 profit Total max profit = 2 + 4 = 6
  3. Step 3: Check for better splits

    Splitting at index 5: first part max profit = 4 (buy at 0 sell at 3), second part max profit = 3 (buy at 1 sell at 4), total = 7
  4. Final Answer:

    7 -> Option C
  5. Quick Check:

    Sum of two best transactions = 7 [OK]
Hint: Split array, sum max profits from two parts [OK]
Common Mistakes:
  • Counting more than two transactions
  • Not splitting array correctly
  • Choosing wrong buy/sell days
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