mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Update 0188.买卖股票的最佳时机IV.md
This commit is contained in:
@ -462,6 +462,33 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
空间优化:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn max_profit(k: i32, prices: Vec<i32>) -> i32 {
|
||||||
|
let mut dp = vec![0; 2 * k as usize + 1];
|
||||||
|
for v in dp.iter_mut().skip(1).step_by(2) {
|
||||||
|
*v = -prices[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
for p in prices {
|
||||||
|
for i in 1..=2 * k as usize {
|
||||||
|
if i % 2 == 1 {
|
||||||
|
// 买入
|
||||||
|
dp[i] = dp[i].max(dp[i - 1] - p);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 卖出
|
||||||
|
dp[i] = dp[i].max(dp[i - 1] + p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dp[2 * k as usize]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
Reference in New Issue
Block a user