From 6c18bfa5024ae7135ba66ae16146c9ff0afc08d3 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 10 Apr 2024 10:55:06 +0800 Subject: [PATCH] 20240410 Finished --- src/problem/mod.rs | 3 +- ...p122_best_time_to_buy_and_sell_stock_ii.rs | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/problem/p122_best_time_to_buy_and_sell_stock_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 0c44635..c689083 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -97,4 +97,5 @@ mod p27_remove_element; mod p80_remove_duplicates_from_sorted_array_ii; mod p169_majority_element; mod p189_rotate_array; -mod p121_best_time_to_buy_and_sell_stock; \ No newline at end of file +mod p121_best_time_to_buy_and_sell_stock; +mod p122_best_time_to_buy_and_sell_stock_ii; \ No newline at end of file diff --git a/src/problem/p122_best_time_to_buy_and_sell_stock_ii.rs b/src/problem/p122_best_time_to_buy_and_sell_stock_ii.rs new file mode 100644 index 0000000..264c983 --- /dev/null +++ b/src/problem/p122_best_time_to_buy_and_sell_stock_ii.rs @@ -0,0 +1,44 @@ +/** + * [122] Best Time to Buy and Sell Stock II + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut result = 0; + let mut once_buy = 0; + let mut min_buy = prices[0]; + + for i in 1..prices.len() { + if prices[i] > prices[i - 1] { + once_buy = once_buy.max(prices[i] - min_buy); + } else if prices[i] < prices[i - 1] { + result += once_buy; + once_buy = 0; + min_buy = prices[i]; + } + } + + if once_buy != 0 { + result += once_buy; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_122() { + assert_eq!(7, Solution::max_profit(vec![7, 1, 5, 3, 6, 4])); + assert_eq!(4, Solution::max_profit(vec![1, 2, 3, 4, 5])); + assert_eq!(0, Solution::max_profit(vec![7, 6, 4, 3, 2, 1])); + } +}