Algo-Sim › Advanced DP

Best Time to Buy and Sell Stock IV

Hard · Advanced DP · step through it in Java, Python and C++ on your own input

At most k transactions: the LC 123 chain grows to 2k states, buy_t and sell_t. When k ≥ n/2 the limit never binds and it becomes LC 122.

Problem

You are given an integer k and prices, where prices[i] is the price of a stock on day i. You may complete at most k transactions (each a buy followed later by a sell), holding at most one share at a time. Return the maximum profit.

Constraints

Edge cases to test

Follow-up questions

Why does k ≥ n/2 change the method?
There can be at most n/2 profitable trades, so the limit never binds; summing rises is O(n) instead of O(n·k).
Is there something faster for huge k and n?
Merge rising runs and use a heap (or the "WQS / Aliens" Lagrangian trick) to get O(n log n).

Solution

Java

public int maxProfit(int k, int[] prices) {
    int n = prices.length;
    if (k >= n / 2) {
        int profit = 0;
        for (int i = 1; i < n; i++) profit += Math.max(0, prices[i] - prices[i - 1]);
        return profit;
    }
    int[] buy = new int[k + 1], sell = new int[k + 1];
    Arrays.fill(buy, Integer.MIN_VALUE);
    for (int p : prices) {
        for (int t = 1; t <= k; t++) {
            buy[t] = Math.max(buy[t], sell[t - 1] - p);
            sell[t] = Math.max(sell[t], buy[t] + p);
        }
    }
    return sell[k];
}

Python

def max_profit(k, prices):
    n = len(prices)
    if k >= n // 2:
        return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, n))
    buy, sell = [float("-inf")] * (k + 1), [0] * (k + 1)
    for p in prices:
        for t in range(1, k + 1):
            buy[t] = max(buy[t], sell[t - 1] - p)
            sell[t] = max(sell[t], buy[t] + p)
    return sell[k]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxProfit(int k, vector<int> &prices) {
        int n = int(prices.size());
        if (k >= n / 2) {
            int profit = 0;
            for (int i = 1; i < n; i++)
                profit += max(0, prices[i] - prices[i - 1]);
            return profit;
        }
        vector<int> buy(k + 1, INT_MIN), sell(k + 1, 0);
        for (int p : prices) {
            for (int t = 1; t <= k; t++) {
                buy[t] = max(buy[t], sell[t - 1] - p);
                sell[t] = max(sell[t], buy[t] + p);
            }
        }
        return sell[k];
    }
};

More Advanced DP problems