diff --git "a/problems/0309.\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237.md" "b/problems/0309.\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237.md" index 4667c122b4..e28e8369e6 100644 --- "a/problems/0309.\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237.md" +++ "b/problems/0309.\346\234\200\344\275\263\344\271\260\345\215\226\350\202\241\347\245\250\346\227\266\346\234\272\345\220\253\345\206\267\345\206\273\346\234\237.md" @@ -207,7 +207,29 @@ class Solution: Go: +Javascript: + +```javascript +const maxProfit = (prices) => { + if(prices.length < 2) { + return 0 + } else if(prices.length < 3) { + return Math.max(0, prices[1] - prices[0]); + } + + let dp = Array.from(Array(prices.length), () => Array(4).fill(0)); + dp[0][0] = 0 - prices[0]; + + for(i = 1; i < prices.length; i++) { + dp[i][0] = Math.max(dp[i - 1][0], Math.max(dp[i-1][1], dp[i-1][3]) - prices[i]); + dp[i][1] = Math.max(dp[i -1][1], dp[i - 1][3]); + dp[i][2] = dp[i-1][0] + prices[i]; + dp[i][3] = dp[i-1][2]; + } + return Math.max(dp[prices.length - 1][1], dp[prices.length - 1][2], dp[prices.length - 1][3]); +}; +``` -----------------------