From 2444c084b15fce271ac3639bca32bc579c594ad1 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 11:33:23 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200188.=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=BAIV.md=20a?= =?UTF-8?q?bout=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 5bed5ecc..8cfb4c1b 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -439,6 +439,28 @@ function maxProfit(k: number, prices: number[]): number { }; ``` +Rust: + +```rust +impl Solution { + pub fn max_profit(k: i32, prices: Vec) -> i32 { + let mut dp = vec![vec![0; 2 * k as usize + 1]; prices.len()]; + + for v in dp[0].iter_mut().skip(1).step_by(2) { + *v = -prices[0]; + } + + for (i, &p) in prices.iter().enumerate().skip(1) { + for j in (0..2 * k as usize - 1).step_by(2) { + dp[i][j + 1] = dp[i - 1][j + 1].max(dp[i - 1][j] - p); + dp[i][j + 2] = dp[i - 1][j + 2].max(dp[i - 1][j + 1] + p); + } + } + + dp[prices.len() - 1][2 * k as usize] + } +} +```

From c4a7033e50a8713808654ac4b179ca4883b4998f Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Fri, 30 Jun 2023 13:45:44 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200188.=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=BAIV.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 8cfb4c1b..fb1a6898 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -462,6 +462,33 @@ impl Solution { } ``` +空间优化: + +```rust +impl Solution { + pub fn max_profit(k: i32, prices: Vec) -> i32 { + let mut dp = vec![0; 2 * k as usize + 1]; + for v in dp.iter_mut().skip(1).step_by(2) { + *v = -prices[0]; + } + + for p in prices { + for i in 1..=2 * k as usize { + if i % 2 == 1 { + // 买入 + dp[i] = dp[i].max(dp[i - 1] - p); + continue; + } + // 卖出 + dp[i] = dp[i].max(dp[i - 1] + p); + } + } + + dp[2 * k as usize] + } +} +``` +