#123
Hard Algorithms Best time to buy and sell stock iii
Array Dynamic Programming
53.2% acceptance
Jan 12, 2026
10534
225
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn max_profit_iii(prices: Vec<i32>) -> i32 {
Self::max_profit(prices)
}
fn max_profit(prices: Vec<i32>) -> i32 {
let mut buy1 = i32::MIN;
let mut sell1 = 0;
let mut buy2 = i32::MIN;
let mut sell2 = 0;
for price in prices {
buy1 = buy1.max(-price);
sell1 = sell1.max(buy1 + price);
buy2 = buy2.max(sell1 - price);
sell2 = sell2.max(buy2 + price);
}
sell2
}
}