Bird
Raised Fist0
DSA Javaprogramming~20 mins

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

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Stock Trading Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Maximum Profit with One Transaction
What is the output of the following Java code that calculates the maximum profit from a single buy-sell transaction?
DSA Java
public class Solution {
    public static int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price;
            } else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice;
            }
        }
        return maxProfit;
    }

    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(prices));
    }
}
A7
B5
C4
D6
Attempts:
2 left
💡 Hint
Track the lowest price and calculate profit at each step.
❓ Predict Output
intermediate
2:00remaining
Maximum Profit with Unlimited Transactions
What is the output of this Java code that calculates the maximum profit with unlimited buy-sell transactions?
DSA Java
public class Solution {
    public static int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                profit += prices[i] - prices[i - 1];
            }
        }
        return profit;
    }

    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(prices));
    }
}
A5
B8
C7
D6
Attempts:
2 left
💡 Hint
Add all positive differences between consecutive days.
❓ Predict Output
advanced
2:30remaining
Maximum Profit with At Most Two Transactions
What is the output of this Java code that calculates the maximum profit with at most two buy-sell transactions?
DSA Java
public class Solution {
    public static int maxProfit(int[] prices) {
        int n = prices.length;
        if (n == 0) return 0;
        int[] leftProfits = new int[n];
        int minPrice = prices[0];
        for (int i = 1; i < n; i++) {
            minPrice = Math.min(minPrice, prices[i]);
            leftProfits[i] = Math.max(leftProfits[i - 1], prices[i] - minPrice);
        }
        int[] rightProfits = new int[n + 1];
        int maxPrice = prices[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            maxPrice = Math.max(maxPrice, prices[i]);
            rightProfits[i] = Math.max(rightProfits[i + 1], maxPrice - prices[i]);
        }
        int maxProfit = 0;
        for (int i = 0; i < n; i++) {
            maxProfit = Math.max(maxProfit, leftProfits[i] + rightProfits[i + 1]);
        }
        return maxProfit;
    }

    public static void main(String[] args) {
        int[] prices = {3,3,5,0,0,3,1,4};
        System.out.println(maxProfit(prices));
    }
}
A6
B5
C7
D4
Attempts:
2 left
💡 Hint
Split the array into two parts and combine profits.
❓ Predict Output
advanced
2:30remaining
Maximum Profit with Cooldown Period
What is the output of this Java code that calculates the maximum profit with cooldown (cannot buy the day after selling)?
DSA Java
public class Solution {
    public static int maxProfit(int[] prices) {
        int n = prices.length;
        if (n <= 1) return 0;
        int[] sell = new int[n];
        int[] buy = new int[n];
        buy[0] = -prices[0];
        sell[0] = 0;
        buy[1] = Math.max(-prices[0], -prices[1]);
        sell[1] = Math.max(0, prices[1] - prices[0]);
        for (int i = 2; i < n; i++) {
            buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]);
            sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]);
        }
        return sell[n - 1];
    }

    public static void main(String[] args) {
        int[] prices = {1, 2, 3, 0, 2};
        System.out.println(maxProfit(prices));
    }
}
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Use arrays to track buy and sell states with cooldown.
🧠 Conceptual
expert
3:00remaining
Understanding State Transitions in Stock Trading with Cooldown
In the cooldown variant of the stock trading problem, which of the following best describes the reason for using sell[i - 2] when calculating buy[i] in the dynamic programming solution?
ABecause sell[i - 2] stores the minimum price before day i.
BBecause the profit on day i-2 is always less than day i-1, so we skip day i-1.
CBecause buying on day i depends on the maximum profit two days before to avoid overlapping transactions.
DBecause after selling on day i-2, day i-1 is a cooldown day, so buying can only happen on day i or later.
Attempts:
2 left
💡 Hint
Think about the cooldown day after selling.

Practice

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

Solution

  1. Step 1: Understand the problem goal

    The problem asks to maximize profit by buying low and selling high on different days.
  2. Step 2: Identify the correct objective

    Maximizing profit means choosing the best buy and sell days, not minimizing transactions or finding averages.
  3. Final Answer:

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

    Goal = Maximize profit [OK]
Hint: Focus on profit difference between buy and sell days [OK]
Common Mistakes:
  • Confusing profit maximization with minimizing transactions
  • Thinking the goal is to find highest price day only
  • Ignoring the buy day before sell day order
2. Which of the following Java code snippets correctly initializes an array of stock prices for 5 days?
easy
A. int[] prices = {7, 1, 5, 3, 6};
B. int prices = [7, 1, 5, 3, 6];
C. int[] prices = (7, 1, 5, 3, 6);
D. int prices[] = 7, 1, 5, 3, 6;

Solution

  1. Step 1: Check Java array initialization syntax

    Java arrays are initialized with curly braces {} and type declaration with [] after type.
  2. Step 2: Validate each option

    Parentheses () are invalid, square brackets [] for values are invalid, missing braces {} and improper assignment are invalid. int[] prices = {7, 1, 5, 3, 6}; uses correct syntax.
  3. Final Answer:

    int[] prices = {7, 1, 5, 3, 6}; -> Option A
  4. Quick Check:

    Correct array syntax = int[] prices = {7, 1, 5, 3, 6}; [OK]
Hint: Use curly braces {} for array values in Java [OK]
Common Mistakes:
  • Using square brackets [] for values instead of curly braces
  • Missing type[] before variable name
  • Using parentheses () instead of braces
3. What is the output of the following Java code that finds max profit with one transaction?
int[] prices = {7, 1, 5, 3, 6, 4};
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
    if (price < minPrice) minPrice = price;
    else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
System.out.println(maxProfit);
medium
A. 5
B. 6
C. 4
D. 7

Solution

  1. Step 1: Track minimum price and max profit during iteration

    Prices: 7,1,5,3,6,4. minPrice updates to 7 then 1. maxProfit updates when price - minPrice is greater.
  2. Step 2: Calculate max profit step-by-step

    At price=5, profit=5-1=4; maxProfit=4. At price=6, profit=6-1=5; maxProfit=5. At price=4, profit=4-1=3; maxProfit stays 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Max profit = 6 - 1 = 5 [OK]
Hint: Track min price and update max profit on the fly [OK]
Common Mistakes:
  • Confusing max profit with max price
  • Not updating minPrice correctly
  • Calculating profit without checking minPrice
4. Identify the error in this Java code snippet that attempts to calculate max profit with multiple transactions:
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
    if (prices[i] > prices[i - 1])
        maxProfit += prices[i] - prices[i - 1];
    else
        i++;
}
System.out.println(maxProfit);
medium
A. Loop should start from i = 0
B. Missing initialization of maxProfit
C. Using prices[i] instead of prices[i-1] in calculation
D. Incorrect increment of loop variable inside else block

Solution

  1. Step 1: Analyze loop increment and conditions

    The loop increments i each iteration, but inside else block it increments i again causing skipping elements.
  2. Step 2: Identify why extra increment causes error

    Extra i++ skips days, missing some profit opportunities and causing incorrect result.
  3. Final Answer:

    Incorrect increment of loop variable inside else block -> Option D
  4. Quick Check:

    Loop variable increment only once per iteration [OK]
Hint: Avoid changing loop variable inside loop body [OK]
Common Mistakes:
  • Incrementing loop variable twice causing skips
  • Starting loop from wrong index
  • Confusing price indices in calculation
5. Given an array of stock prices, how would you modify the algorithm to find the maximum profit with at most two transactions? Choose the best approach.
hard
A. Buy on the lowest price day and sell on the highest price day only.
B. Use two passes: first pass calculates max profit up to each day, second pass calculates max profit from each day to end, then combine.
C. Use a single pass and sum all positive differences between consecutive days.
D. Sort the prices array and pick the two largest differences.

Solution

  1. Step 1: Understand the two transaction constraint

    At most two transactions means we can buy and sell twice, but transactions cannot overlap.
  2. Step 2: Use two-pass approach for max profit calculation

    First pass calculates max profit from day 0 to i, second pass calculates max profit from i to end. Combining these gives max profit with two transactions.
  3. Final Answer:

    Use two passes: first pass calculates max profit up to each day, second pass calculates max profit from each day to end, then combine. -> Option B
  4. Quick Check:

    Two-pass method = Use two passes: first pass calculates max profit up to each day, second pass calculates max profit from each day to end, then combine. [OK]
Hint: Split problem into two single-transaction profits [OK]
Common Mistakes:
  • Sorting prices loses day order information
  • Summing all positive differences allows unlimited transactions
  • Ignoring transaction count limit
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