diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 146c6a4c..5976f258 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -346,7 +346,52 @@ public class Solution } ``` +Rust: +> 贪心 + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut result = 0; + for i in 1..prices.len() { + result += (prices[i] - prices[i - 1]).max(0); + } + result + } +} +``` + +>动态规划 + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut dp = vec![vec![0; 2]; prices.len()]; + dp[0][0] = -prices[0]; + for i in 1..prices.len() { + dp[i][0] = dp[i - 1][0].max(dp[i - 1][1] - prices[i]); + dp[i][1] = dp[i - 1][1].max(dp[i - 1][0] + prices[i]); + } + dp[prices.len() - 1][1] + } +} +``` + +> 优化 + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut dp = vec![-prices[0], 0]; + for i in 1..=prices.len() { + dp[0] = dp[0].max(dp[1] - prices[i - 1]); + dp[1] = dp[1].max(dp[0] + prices[i - 1]); + } + dp[1] + } +} +```