123. Best Time to Buy and Sell Stock III
Asked at 13Meta45Microsoft36Apple35Amazon33Google29Bloomberg28Infosys39Tekion82Snap68PayPal42Visa39TikTok35Goldman Sachs33
Problem
prices[i] is a stock's price on day i. Make at most two buy-then-sell transactions (holding at most one share at a time) and return the maximum profit.
Example: [3,3,5,0,0,3,1,4] → 6; [1,2,3,4,5] → 4
Constraints: n ≤ 10⁵.
At most two transactions → four running states: buy1, sell1, buy2, sell2. Each is the best balance after that action so far; buy2 builds on sell1.
Complexity: O(n) time, O(1) space.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy1 = buy2 = float("-inf")
sell1 = sell2 = 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
assert Solution().maxProfit([3, 3, 5, 0, 0, 3, 1, 4]) == 6
assert Solution().maxProfit([1, 2, 3, 4, 5]) == 4
assert Solution().maxProfit([7, 6, 4, 3, 1]) == 0
class Solution {
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;
}
}
func maxProfit(prices []int) int {
buy1, buy2 := math.MinInt/2, math.MinInt/2
sell1, sell2 := 0, 0
for _, p := range prices {
buy1 = max(buy1, -p)
sell1 = max(sell1, buy1+p)
buy2 = max(buy2, sell1-p) // the second buy is paid from the first profit
sell2 = max(sell2, buy2+p)
}
return sell2
}