mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0714.买卖股票的最佳时机含手续费(动态规划) Rust版本
添加 0714.买卖股票的最佳时机含手续费(动态规划) Rust版本
This commit is contained in:
@ -221,8 +221,46 @@ function maxProfit(prices: number[], fee: number): number {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Rust:
|
||||||
|
**贪心**
|
||||||
|
```Rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn max_profit(prices: Vec<i32>, fee: i32) -> i32 {
|
||||||
|
let mut result = 0;
|
||||||
|
let mut min_price = prices[0];
|
||||||
|
for i in 1..prices.len() {
|
||||||
|
if prices[i] < min_price { min_price = prices[i]; }
|
||||||
|
|
||||||
|
// if prices[i] >= min_price && prices[i] <= min_price + fee { continue; }
|
||||||
|
|
||||||
|
if prices[i] > min_price + fee {
|
||||||
|
result += prices[i] - min_price - fee;
|
||||||
|
min_price = prices[i] - fee;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**动态规划**
|
||||||
|
```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 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);
|
||||||
|
}
|
||||||
|
Self::max(dp[n - 1][0], dp[n - 1][1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user