diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 1443f147..9aa82d4a 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -270,18 +270,29 @@ impl Solution { **动态规划** ```Rust impl Solution { - fn max(a: i32, b: i32) -> i32 { - if a > b { a } else { b } - } pub fn max_profit(prices: Vec, fee: i32) -> 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] - fee); + let mut dp = vec![vec![0; 2]; prices.len()]; + dp[0][0] = -prices[0]; + for (i, &p) in prices.iter().enumerate().skip(1) { + dp[i][0] = dp[i - 1][0].max(dp[i - 1][1] - p); + dp[i][1] = dp[i - 1][1].max(dp[i - 1][0] + p - fee); } - Self::max(dp[n - 1][0], dp[n - 1][1]) + dp[prices.len() - 1][1] + } +} +``` + +**动态规划优化** + +```rust +impl Solution { + pub fn max_profit(prices: Vec, fee: i32) -> i32 { + let (mut low, mut res) = (-prices[0], 0); + for p in prices { + low = low.max(res - p); + res = res.max(p + low - fee); + } + res } } ```