</>

188. Best Time to Buy and Sell Stock IV

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

Quick review

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

Standard Solution (C++)

SummaryGiven a list of daily stock prices and a maximum of k transactions (each consisting of one buy followed by one sell), find the maximum profit achievable without holding more than one share at a time.

Approach
  • Track two arrays: buy[j] = best profit after completing j-1 sells and currently holding a share, and sell[j] = best profit after completing exactly j full transactions.
  • For each price, update buy[j] = max(buy[j], sell[j-1] - price) (buy on this day using profit from j-1 prior transactions) and sell[j] = max(sell[j], buy[j] + price) (sell on this day closing the j-th transaction).
  • Iterating j from 1 to k within each day processes transactions in order; buying and selling on the same day yields zero marginal gain so correctness is preserved.
  • Return sell[k], the maximum profit with at most k complete transactions.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        if (n == 0 || k == 0) return 0;

        // buy[j]  = best portfolio value after holding a share, having used j-1 sells
        // sell[j] = best portfolio value after completing exactly j full round-trips
        vector<int> buy(k + 1, INT_MIN / 2); // initialise to -infinity
        vector<int> sell(k + 1, 0);          // 0 transactions, 0 profit

        for (int price : prices) {
            for (int j = 1; j <= k; j++) {
                buy[j]  = max(buy[j],  sell[j - 1] - price); // open j-th buy
                sell[j] = max(sell[j], buy[j]      + price); // close j-th sell
            }
        }

        return sell[k]; // max profit with at most k transactions
    }
};
Time O(n * k) Space O(k)

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

My Solution (C++)

class Solution {
public:
/*
    int maxProfit(int k, vector<int>& prices) {
        int n=prices.size();
        vector<vector<vector<int>>> dp(2, vector<vector<int>>(k+1, 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]);
            for(int j=1; j<k; j++){
                dp[1][j][0]=max(dp[0][j][0], dp[0][j-1][1]+prices[i]);
                dp[1][j][1]=max(dp[0][j][1], dp[0][j][0]-prices[i]);
            }
            dp[1][k][0]=max(dp[0][k][0], dp[0][k-1][1]+prices[i]);

            dp[0][0][1]=dp[1][0][1];
            for(int j=1; j<k; j++){
                dp[0][j][0]=dp[1][j][0];
                dp[0][j][1]=dp[1][j][1];
            }
            dp[0][k][0]=dp[1][k][0];
        }

        int result=0;
        for(int i=1; i<=k; i++)
            result=max(result, dp[1][i][0]);
        return result; 
    }
*/
    int maxProfit(int k, vector<int>& prices) {
        int n=prices.size();

        vector<int> buy(k+1, -1e5); // ending with buy j times
        vector<int> sell(k+1, 0); // ending with buy and sell j times

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

        return sell[k];
    }
};

// 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