KatInterview

188. Best Time to Buy and Sell Stock IV

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

This problem asks for the maximum profit from at most k stock transactions. It's a generalization of the 'Best Time to Buy and Sell Stock' series. The core challenge is to make optimal decisions (buy, sell, or do nothing) on each day to maximize profit, given the constraint on the number of transactions.

Solution

Best Time to Buy and Sell Stock IV in Python

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        n = len(prices)
        if n < 2 or k == 0:
            return 0

        # If k is large enough, it's equivalent to unlimited transactions.
        # This is the solution for Best Time to Buy and Sell Stock II.
        if k >= n // 2:
            max_profit = 0
            for i in range(1, n):
                if prices[i] > prices[i-1]:
                    max_profit += prices[i] - prices[i-1]
            return max_profit

        # DP solution for at most k transactions
        # holds[j]: max profit after j-th buy
        # sells[j]: max profit after j-th sell
        holds = [float('-inf')] * (k + 1)
        sells = [0] * (k + 1)

        for price in prices:
            for j in range(1, k + 1):
                # The maximum profit after j-th buy is the max of:
                # 1. Not buying today (keeping the profit from previous day's j-th buy).
                # 2. Buying today (profit from (j-1)-th sell minus today's price).
                holds[j] = max(holds[j], sells[j-1] - price)
                
                # The maximum profit after j-th sell is the max of:
                # 1. Not selling today (keeping the profit from previous day's j-th sell).
                # 2. Selling today (profit from j-th buy plus today's price).
                sells[j] = max(sells[j], holds[j] + price)

        return sells[k]

Best Time to Buy and Sell Stock IV in Java

class Solution {
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        if (n < 2 || k == 0) {
            return 0;
        }

        // If k is large enough, it's equivalent to unlimited transactions.
        // This is the solution for Best Time to Buy and Sell Stock II.
        if (k >= n / 2) {
            int maxProfit = 0;
            for (int i = 1; i < n; i++) {
                if (prices[i] > prices[i - 1]) {
                    maxProfit += prices[i] - prices[i - 1];
                }
            }
            return maxProfit;
        }

        // DP solution for at most k transactions
        // holds[j]: max profit after j-th buy
        // sells[j]: max profit after j-th sell
        int[] holds = new int[k + 1];
        int[] sells = new int[k + 1];
        Arrays.fill(holds, Integer.MIN_VALUE);

        for (int price : prices) {
            for (int j = 1; j <= k; j++) {
                // The maximum profit after j-th buy is the max of:
                // 1. Not buying today (keeping the profit from previous day's j-th buy).
                // 2. Buying today (profit from (j-1)-th sell minus today's price).
                holds[j] = Math.max(holds[j], sells[j - 1] - price);

                // The maximum profit after j-th sell is the max of:
                // 1. Not selling today (keeping the profit from previous day's j-th sell).
                // 2. Selling today (profit from j-th buy plus today's price).
                sells[j] = Math.max(sells[j], holds[j] + price);
            }
        }

        return sells[k];
    }
}

Best Time to Buy and Sell Stock IV in C++

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

        // If k is large enough, it's equivalent to unlimited transactions.
        if (k >= n / 2) {
            int max_profit = 0;
            for (int i = 1; i < n; ++i) {
                if (prices[i] > prices[i - 1]) {
                    max_profit += prices[i] - prices[i - 1];
                }
            }
            return max_profit;
        }

        // DP solution for at most k transactions
        // holds[j]: max profit after j-th buy
        // sells[j]: max profit after j-th sell
        vector<int> holds(k + 1, INT_MIN);
        vector<int> sells(k + 1, 0);

        for (int price : prices) {
            for (int j = 1; j <= k; ++j) {
                // The maximum profit after j-th buy is the max of:
                // 1. Not buying today (keeping the profit from previous day's j-th buy).
                // 2. Buying today (profit from (j-1)-th sell minus today's price).
                holds[j] = max(holds[j], sells[j - 1] - price);
                
                // The maximum profit after j-th sell is the max of:
                // 1. Not selling today (keeping the profit from previous day's j-th sell).
                // 2. Selling today (profit from j-th buy plus today's price).
                sells[j] = max(sells[j], holds[j] + price);
            }
        }

        return sells[k];
    }
};

Best Time to Buy and Sell Stock IV in TypeScript

function maxProfit(k: number, prices: number[]): number {
    const n = prices.length;
    if (n < 2 || k === 0) {
        return 0;
    }

    // If k is large enough, it's equivalent to unlimited transactions.
    // This is the solution for Best Time to Buy and Sell Stock II.
    if (k >= Math.floor(n / 2)) {
        let maxProfit = 0;
        for (let i = 1; i < n; i++) {
            if (prices[i] > prices[i - 1]) {
                maxProfit += prices[i] - prices[i - 1];
            }
        }
        return maxProfit;
    }

    // DP solution for at most k transactions
    // holds[j]: max profit after j-th buy
    // sells[j]: max profit after j-th sell
    const holds = new Array(k + 1).fill(Number.NEGATIVE_INFINITY);
    const sells = new Array(k + 1).fill(0);

    for (const price of prices) {
        for (let j = 1; j <= k; j++) {
            // The maximum profit after j-th buy is the max of:
            // 1. Not buying today (keeping the profit from previous day's j-th buy).
            // 2. Buying today (profit from (j-1)-th sell minus today's price).
            holds[j] = Math.max(holds[j], sells[j - 1] - price);

            // The maximum profit after j-th sell is the max of:
            // 1. Not selling today (keeping the profit from previous day's j-th sell).
            // 2. Selling today (profit from j-th buy plus today's price).
            sells[j] = Math.max(sells[j], holds[j] + price);
        }
    }

    return sells[k];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.