709515. Stock Buy and Sell – Max 2 Transactions Allowed

Hard

Buy and Sell a Share at Most Twice

Summary

This problem involves finding the maximum profit that can be achieved by buying and selling a share at most twice, given an array of prices. The key concepts involved are arrays, dynamic programming, and optimization.

Detailed Explanation

The problem requires us to find the maximum possible profit from buying and selling a share at most twice. We can solve this problem using dynamic programming.

Let's define two variables buy1 and sell1 that store the maximum profit we can get after the first buy and sell respectively, and similarly let's define buy2 and sell2 for the second buy and sell. Initially, buy1 is negative infinity because we have to spend money to buy the share initially, and sell1, buy2, and sell2 are all zero.

Now, let's iterate over the array of prices. For each price, we update our variables as follows:

  • If this is the first day, then buy1 is updated to be the maximum of its current value and -price, because we can either choose not to buy or spend money to buy the share.
  • If this is the second day, then sell1 is updated to be the maximum of its current value and price + buy1, because we can either choose not to sell or sell the share at this price if we bought it earlier.
  • Similarly, for the second buy and sell, we update buy2 as the maximum of its current value and -min(price, sell1), because we can only buy after selling in the first transaction. Then we update sell2 as the maximum of its current value and price + buy2.

Finally, our answer is max(sell1, sell2).

Here's a step-by-step breakdown:

buy1 = -∞
sell1 = 0
buy2 = 0
sell2 = 0

for each price in prices:
    if this is the first day:
        buy1 = max(buy1, -price)
    elif this is the second day:
        sell1 = max(sell1, price + buy1)

    if this is the second buy and sell day:
        buy2 = max(buy2, -min(price, sell1))
        sell2 = max(sell2, price + buy2)

answer = max(sell1, sell2)

Time complexity: O(n), where n is the number of days. Space complexity: O(1).

Optimized Solutions

Java

View on GeeksforGeeks
public int maxProfit(int[] prices) {
    if (prices.length < 2) return 0;
    
    int buy1 = Integer.MIN_VALUE, sell1 = 0, buy2 = 0, sell2 = 0;
    
    for (int price : prices) {
        buy1 = Math.max(buy1, -price);
        sell1 = Math.max(sell1, price + buy1);
        
        buy2 = Math.max(buy2, -Math.min(price, sell1));
        sell2 = Math.max(sell2, price + buy2);
    }
    
    return Math.max(sell1, sell2);
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.