Skip to content

Commit b64df0f

Browse files
Merge pull request youngyangyang04#485 from jackeyjia/patch-9
add js solution for maxProfit IV
2 parents 3d41c31 + 486fff2 commit b64df0f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

problems/0188.买卖股票的最佳时机IV.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,30 @@ class Solution:
258258
Go:
259259

260260

261+
Javascript:
261262

263+
```javascript
264+
const maxProfit = (k,prices) => {
265+
if (prices == null || prices.length < 2 || k == 0) {
266+
return 0;
267+
}
268+
269+
let dp = Array.from(Array(prices.length), () => Array(2*k+1).fill(0));
270+
271+
for (let j = 1; j < 2 * k; j += 2) {
272+
dp[0][j] = 0 - prices[0];
273+
}
274+
275+
for(let i = 1; i < prices.length; i++) {
276+
for (let j = 0; j < 2 * k; j += 2) {
277+
dp[i][j+1] = Math.max(dp[i-1][j+1], dp[i-1][j] - prices[i]);
278+
dp[i][j+2] = Math.max(dp[i-1][j+2], dp[i-1][j+1] + prices[i]);
279+
}
280+
}
281+
282+
return dp[prices.length - 1][2 * k];
283+
};
284+
```
262285

263286
-----------------------
264287
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)