From fd7a98b8315eb56f07caac3cc586f6b96e3d246b Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Sat, 3 Jun 2023 14:40:00 +0800 Subject: [PATCH] =?UTF-8?q?Update=200122.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAII?= =?UTF-8?q?=EF=BC=88=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=EF=BC=89.md=20abo?= =?UTF-8?q?ut=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...¡ç¥¨çš„æœ€ä½³æ—¶æœºII(动æ€è§„划).md | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) 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] + } +} +```