Skip to content

Commit c2e3d10

Browse files
Merge pull request youngyangyang04#486 from jackeyjia/patch-10
add js solution for maxProfit with Cooldown
2 parents b64df0f + e267f10 commit c2e3d10

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

problems/0309.最佳买卖股票时机含冷冻期.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,29 @@ class Solution:
207207

208208
Go:
209209

210+
Javascript:
211+
212+
```javascript
213+
const maxProfit = (prices) => {
214+
if(prices.length < 2) {
215+
return 0
216+
} else if(prices.length < 3) {
217+
return Math.max(0, prices[1] - prices[0]);
218+
}
219+
220+
let dp = Array.from(Array(prices.length), () => Array(4).fill(0));
221+
dp[0][0] = 0 - prices[0];
222+
223+
for(i = 1; i < prices.length; i++) {
224+
dp[i][0] = Math.max(dp[i - 1][0], Math.max(dp[i-1][1], dp[i-1][3]) - prices[i]);
225+
dp[i][1] = Math.max(dp[i -1][1], dp[i - 1][3]);
226+
dp[i][2] = dp[i-1][0] + prices[i];
227+
dp[i][3] = dp[i-1][2];
228+
}
210229

230+
return Math.max(dp[prices.length - 1][1], dp[prices.length - 1][2], dp[prices.length - 1][3]);
231+
};
232+
```
211233

212234

213235
-----------------------

0 commit comments

Comments
 (0)