Algo-Sim › Dynamic Programming

Best Time to Buy and Sell Stock III

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

At most two transactions. Four states (buy1, sell1, buy2, sell2) form a chain, each updated once per day.

Problem

You are given prices, where prices[i] is the price of a stock on day i. You may complete at most two transactions (two buys and two sells), and you must sell before you buy again. Return the maximum profit.

Constraints

Edge cases to test

Follow-up questions

What about at most k trades?
Keep 2k states (buy₁, sell₁ … buyₖ, sellₖ): O(n·k); if k ≥ n/2 it is unlimited trading (LC 188).
Is there a split-point view?
Best one-trade profit on the left of each day plus best on the right: two O(n) passes.

Solution

Java

public int maxProfit(int[] prices) {
    int buy1 = Integer.MIN_VALUE, sell1 = 0, buy2 = Integer.MIN_VALUE, sell2 = 0;
    for (int p : prices) {
        buy1 = Math.max(buy1, -p);
        sell1 = Math.max(sell1, buy1 + p);
        buy2 = Math.max(buy2, sell1 - p);
        sell2 = Math.max(sell2, buy2 + p);
    }
    return sell2;
}

Python

def max_profit(prices):
    buy1, sell1, buy2, sell2 = float("-inf"), 0, float("-inf"), 0
    for p in prices:
        buy1 = max(buy1, -p)
        sell1 = max(sell1, buy1 + p)
        buy2 = max(buy2, sell1 - p)
        sell2 = max(sell2, buy2 + p)
    return sell2

C++

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

class Solution {
  public:
    int maxProfit(vector<int> &prices) {
        int buy1 = INT_MIN, sell1 = 0, buy2 = INT_MIN, sell2 = 0;
        for (int p : prices) {
            buy1 = max(buy1, -p);
            sell1 = max(sell1, buy1 + p);
            buy2 = max(buy2, sell1 - p);
            sell2 = max(sell2, buy2 + p);
        }
        return sell2;
    }
};

More Dynamic Programming problems