From c7a090afa408902f2ee9a8b61c20d96655b7e6f6 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 14 Aug 2024 10:57:20 +0800 Subject: [PATCH] 20240814 Finished --- src/problem/mod.rs | 3 +- ...p188_best_time_to_buy_and_sell_stock_iv.rs | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 8166919..fa7e77a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -203,4 +203,5 @@ mod p64_minimum_path_sum; mod p63_unique_paths_ii; mod p97_interleaving_string; mod p72_edit_distance; -mod p123_best_time_to_buy_and_sell_stock_iii; \ No newline at end of file +mod p123_best_time_to_buy_and_sell_stock_iii; +mod p188_best_time_to_buy_and_sell_stock_iv; \ No newline at end of file diff --git a/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs b/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs new file mode 100644 index 0000000..01291d8 --- /dev/null +++ b/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs @@ -0,0 +1,42 @@ +/** + * [188] Best Time to Buy and Sell Stock IV + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn max_profit(k: i32, prices: Vec) -> i32 { + let n = prices.len(); + let k = k as usize; + + let mut dp = vec![(-prices[0], 0); k]; + + for i in 1..n { + for j in 0..k { + dp[j].0 = dp[j].0.max(if j == 0 { + -prices[i] + } else { + dp[j - 1].1 - prices[i] + }); + dp[j].1 = dp[j].1.max(dp[j].0 + prices[i]); + } + } + + dp[k - 1].1 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_188() { + assert_eq!(2, Solution::max_profit(2, vec![2, 4, 1])); + assert_eq!(7, Solution::max_profit(2, vec![3, 2, 6, 5, 0, 3])); + } +}