mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #2124 from fwqaaq/patch-38
Update 0122.买卖股票的最佳时机II(动态规划).md about rust
This commit is contained in:
@ -346,7 +346,52 @@ public class Solution
|
||||
}
|
||||
```
|
||||
|
||||
Rust:
|
||||
|
||||
> 贪心
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
||||
let mut result = 0;
|
||||
for i in 1..prices.len() {
|
||||
result += (prices[i] - prices[i - 1]).max(0);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
>动态规划
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
||||
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]);
|
||||
}
|
||||
dp[prices.len() - 1][1]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 优化
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
||||
let mut dp = vec![-prices[0], 0];
|
||||
for p in prices {
|
||||
dp[0] = dp[0].max(dp[1] - p);
|
||||
dp[1] = dp[1].max(dp[0] + p);
|
||||
}
|
||||
dp[1]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user