添加 0122.买卖股票的最佳时机II Rust版本

添加 0122.买卖股票的最佳时机II Rust版本(贪心+动态规划)
This commit is contained in:
cezarbbb
2022-07-26 10:35:31 +08:00
parent 95e9296301
commit b80591ef85

View File

@ -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>) -> 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>) -> 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