From b80591ef85f2efb1f0917c7e0144bc7f5f15e81f Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 26 Jul 2022 10:35:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200122.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?II=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0122.买卖股票的最佳时机II Rust版本(贪心+动态规划) --- .../0122.买卖股票的最佳时机II.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index e4742cf0..1094d9e4 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -282,6 +282,43 @@ function maxProfit(prices: number[]): number { }; ``` +### Rust + +贪心: +```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 + } +} +``` + +动态规划: +```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]); + } + Self::max(dp[n - 1][0], dp[n - 1][1]) + } +} +``` + ### C: 贪心: ```c