Skip to content

Commit 3cff2bb

Browse files
authored
add js solution for maxProfit IV
1 parent a9344c2 commit 3cff2bb

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,31 @@ class Solution:
230230
Go:
231231

232232

233+
Javascript:
234+
235+
```javascript
236+
const maxProfit = (k,prices) => {
237+
if (prices == null || prices.length < 2 || k == 0) {
238+
return 0;
239+
}
240+
241+
let dp = Array.from(Array(prices.length), () => Array(2*k+1).fill(0));
242+
243+
for (let j = 1; j < 2 * k; j += 2) {
244+
dp[0][j] = 0 - prices[0];
245+
}
246+
247+
for(let i = 1; i < prices.length; i++) {
248+
for (let j = 0; j < 2 * k; j += 2) {
249+
dp[i][j+1] = Math.max(dp[i-1][j+1], dp[i-1][j] - prices[i]);
250+
dp[i][j+2] = Math.max(dp[i-1][j+2], dp[i-1][j+1] + prices[i]);
251+
}
252+
}
253+
254+
return dp[prices.length - 1][2 * k];
255+
};
256+
```
257+
233258

234259

235260
-----------------------

0 commit comments

Comments
 (0)