Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 7 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Jul 21, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Update 0714.买卖股票的最佳时机含手续费(动态规划).md 优化 Rust
  • Loading branch information
fwqaaq authored Jun 30, 2023
commit e563783a71fe3de6564c7c01e8ffbfc961f3efee
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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<i32>, fee: i32) -> i32 {
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);
}
dp[prices.len() - 1][1]
}
}
```

**动态规划优化**

```rust
impl Solution {
pub fn max_profit(prices: Vec<i32>, 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 low, mut res) = (-prices[0], 0);
for p in prices {
low = low.max(res - p);
res = res.max(p + low - fee);
}
Self::max(dp[n - 1][0], dp[n - 1][1])
res
}
}
```
Expand Down

AltStyle によって変換されたページ (->オリジナル) /