</>

123. Best Time to Buy and Sell Stock III

Hard
1-D Dynamic Programming Time O(n) Space O(1)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
1-D Dynamic Programming
Time
O(n)
Space
O(1)

Standard Solution (C++)

SummaryGiven a list of daily stock prices, find the maximum profit achievable by completing at most two buy-sell transactions, where each buy must occur before its corresponding sell and you may not hold more than one share at a time.

Approach
  • Track four state variables: the best profit after the 1st buy, after the 1st sell, after the 2nd buy, and after the 2nd sell.
  • For each price, update states in order (buy1, sell1, buy2, sell2) so that each state builds on the most-recently-updated earlier state within the same pass.
  • buy1 minimizes cost of the first purchase; sell1 maximizes profit after the first sale; buy2 nets the second purchase against prior profit; sell2 is the final answer.
  • A single O(n) pass over prices with O(1) extra space suffices because each state depends only on the immediately preceding state.
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // buy1: max profit after first buy  (negative cost)
        // sell1: max profit after first sell
        // buy2: max profit after second buy (sell1 minus new cost)
        // sell2: max profit after second sell — the answer
        int buy1 = INT_MIN, sell1 = 0;
        int buy2 = INT_MIN, sell2 = 0;

        for (int price : prices) {
            buy1  = max(buy1,        -price);       // pay price for 1st share
            sell1 = max(sell1, buy1  + price);      // sell 1st share
            buy2  = max(buy2,  sell1 - price);      // pay price for 2nd share
            sell2 = max(sell2, buy2  + price);      // sell 2nd share
        }

        return sell2;  // 0 if no profitable transaction exists
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
/*
    int maxProfit(vector<int>& prices) {
        int n=prices.size(); // n is the total number of days
        // dp[i][k][0/1] means day i, already k transactions, notHold/hold
        vector<vector<vector<int>>> dp(n, vector<vector<int>>(3, vector<int>(2, -1e5)));

        // initialization
        dp[0][0][1]=-prices[0];

        for(int i=1; i<n; i++){
            dp[i][0][1]=max(dp[i-1][0][1], -prices[i]);
            dp[i][1][0]=max(dp[i-1][1][0], dp[i-1][0][1]+prices[i]);
            dp[i][1][1]=max(dp[i-1][1][1], dp[i-1][1][0]-prices[i]);
            dp[i][2][0]=max(dp[i-1][2][0], dp[i-1][1][1]+prices[i]);
        }

        int result=max(dp[n-1][1][0], dp[n-1][2][0]);

        return max(0, result);
    }
*/
/*
    int maxProfit(vector<int>& prices) {
        int n=prices.size();
        vector<vector<vector<int>>> dp(2, vector<vector<int>>(3, vector<int>(2, -1e5)));
        dp[0][0][1]=-prices[0];

        for(int i=1; i<n; i++){
            dp[1][0][1]=max(dp[0][0][1], -prices[i]);
            dp[1][1][0]=max(dp[0][1][0], dp[0][0][1]+prices[i]);
            dp[1][1][1]=max(dp[0][1][1], dp[0][1][0]-prices[i]);
            dp[1][2][0]=max(dp[0][2][0], dp[0][1][1]+prices[i]);

            dp[0][0][1]=dp[1][0][1];
            dp[0][1][0]=dp[1][1][0];
            dp[0][1][1]=dp[1][1][1];
            dp[0][2][0]=dp[1][2][0];
        }

        int result=max(dp[1][1][0], dp[1][2][0]);

        return max(0, result); 
    }
*/
    int maxProfit(vector<int>& prices) {
        int n=prices.size();

        vector<int> buy(3, -1e5); // buy[j] ending with the jth buy
        vector<int> sell(3, 0); // sell[j] ending with the jth sell

        for(int price: prices){
            for(int j=1; j<=2; j++){
                buy[j]=max(buy[j], sell[j-1]-price);
                sell[j]=max(sell[j], buy[j]+price);
            }
        }

        return sell[2];
    }
};

// Time Complexity: O(n)
// Space Complexity: O(1)
Time O(n) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern