diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 27b880f..8166919 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -202,4 +202,5 @@ mod p120_triangle; mod p64_minimum_path_sum; mod p63_unique_paths_ii; mod p97_interleaving_string; -mod p72_edit_distance; \ No newline at end of file +mod p72_edit_distance; +mod p123_best_time_to_buy_and_sell_stock_iii; \ No newline at end of file diff --git a/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs b/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs new file mode 100644 index 0000000..0858fd8 --- /dev/null +++ b/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs @@ -0,0 +1,37 @@ +/** + * [123] Best Time to Buy and Sell Stock III + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let n = prices.len(); + let (mut buy1, mut sell1) = (-prices[0], 0); + let (mut buy2, mut sell2) = (-prices[0], 0); + + for i in 1..n { + buy1 = buy1.max(-prices[i]); + sell1 = sell1.max(buy1 + prices[i]); + buy2 = buy2.max(sell1 - prices[i]); + sell2 = sell2.max(buy2 + prices[i]); + } + + sell2 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_123() { + assert_eq!(4, Solution::max_profit(vec![1, 2, 3, 4, 5])); + assert_eq!(6, Solution::max_profit(vec![3, 3, 5, 0, 0, 3, 1, 4])); + } +}