mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2123 from fwqaaq/patch-37
Update 0122.买卖股票的最佳时机II.md 优化 Rust
This commit is contained in:
@ -322,13 +322,10 @@ function maxProfit(prices: number[]): number {
|
|||||||
|
|
||||||
```Rust
|
```Rust
|
||||||
impl Solution {
|
impl Solution {
|
||||||
fn max(a: i32, b: i32) -> i32 {
|
|
||||||
if a > b { a } else { b }
|
|
||||||
}
|
|
||||||
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
||||||
let mut result = 0;
|
let mut result = 0;
|
||||||
for i in 1..prices.len() {
|
for i in 1..prices.len() {
|
||||||
result += Self::max(prices[i] - prices[i - 1], 0);
|
result += (prices[i] - prices[i - 1]).max(0);
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
@ -339,18 +336,14 @@ impl Solution {
|
|||||||
|
|
||||||
```Rust
|
```Rust
|
||||||
impl Solution {
|
impl Solution {
|
||||||
fn max(a: i32, b: i32) -> i32 {
|
|
||||||
if a > b { a } else { b }
|
|
||||||
}
|
|
||||||
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
pub fn max_profit(prices: Vec<i32>) -> i32 {
|
||||||
let n = prices.len();
|
let mut dp = vec![vec![0; 2]; prices.len()];
|
||||||
let mut dp = vec![vec![0; 2]; n];
|
dp[0][0] = -prices[0];
|
||||||
dp[0][0] -= prices[0];
|
for i in 1..prices.len() {
|
||||||
for i in 1..n {
|
dp[i][0] = dp[i - 1][0].max(dp[i - 1][1] - prices[i]);
|
||||||
dp[i][0] = Self::max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
|
dp[i][1] = dp[i - 1][1].max(dp[i - 1][0] + 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])
|
dp[prices.len() - 1][1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user