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
- 1 ≤ prices.length ≤ 10⁵
- 0 ≤ prices[i] ≤ 10⁵
- At most 2 transactions, at most one share at a time
Edge cases to test
- Fewer than two profitable trades
- Prices only fall
- One long rise (one trade is best)
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 sell2C++
#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
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)