From 745e91e1e7043474e15ec790a89a472d0d25e279 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Sat, 3 Jun 2023 14:22:19 +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.md=20?= =?UTF-8?q?=E4=BC=98=E5=8C=96=20Rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0122.买卖股票的最佳时机II.md | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 0d8ad608..89c654fa 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -322,13 +322,10 @@ function maxProfit(prices: number[]): number { ```Rust impl Solution { - fn max(a: i32, b: i32) -> i32 { - if a > b { a } else { b } - } pub fn max_profit(prices: Vec) -> i32 { let mut result = 0; for i in 1..prices.len() { - result += Self::max(prices[i] - prices[i - 1], 0); + result += (prices[i] - prices[i - 1]).max(0); } result } @@ -339,18 +336,14 @@ impl Solution { ```Rust impl Solution { - fn max(a: i32, b: i32) -> i32 { - if a > b { a } else { b } - } pub fn max_profit(prices: Vec) -> i32 { - let n = prices.len(); - let mut dp = vec![vec![0; 2]; n]; - dp[0][0] -= prices[0]; - for i in 1..n { - dp[i][0] = Self::max(dp[i - 1][0], dp[i - 1][1] - prices[i]); - dp[i][1] = Self::max(dp[i - 1][1], dp[i - 1][0] + prices[i]); + 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]); } - Self::max(dp[n - 1][0], dp[n - 1][1]) + dp[prices.len() - 1][1] } } ```