mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
0188 买卖股票最佳时机IV JavaScript 添加 动态规划+空间优化 解法
This commit is contained in:
@ -280,6 +280,7 @@ Go:
|
|||||||
Javascript:
|
Javascript:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
// 方法一:动态规划
|
||||||
const maxProfit = (k,prices) => {
|
const maxProfit = (k,prices) => {
|
||||||
if (prices == null || prices.length < 2 || k == 0) {
|
if (prices == null || prices.length < 2 || k == 0) {
|
||||||
return 0;
|
return 0;
|
||||||
@ -300,6 +301,30 @@ const maxProfit = (k,prices) => {
|
|||||||
|
|
||||||
return dp[prices.length - 1][2 * k];
|
return dp[prices.length - 1][2 * k];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 方法二:动态规划+空间优化
|
||||||
|
var maxProfit = function(k, prices) {
|
||||||
|
let n = prices.length;
|
||||||
|
let dp = new Array(2*k+1).fill(0);
|
||||||
|
// dp 买入状态初始化
|
||||||
|
for (let i = 1; i <= 2*k; i += 2) {
|
||||||
|
dp[i] = - prices[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 1; i < n; i++) {
|
||||||
|
for (let j = 1; j < 2*k+1; j++) {
|
||||||
|
// j 为奇数:买入状态
|
||||||
|
if (j % 2) {
|
||||||
|
dp[j] = Math.max(dp[j], dp[j-1] - prices[i]);
|
||||||
|
} else {
|
||||||
|
// j为偶数:卖出状态
|
||||||
|
dp[j] = Math.max(dp[j], dp[j-1] + prices[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return dp[2*k];
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user