feat(0309): 另一种状态定义思路

This commit is contained in:
eat to 160 pounds
2024-07-13 15:10:24 +08:00
parent 89ac69f7d8
commit 9b9adf6100

View File

@ -359,6 +359,26 @@ func max(a, b int) int {
### Javascript:
> 不同的状态定义 感觉更容易理解些
```javascript
function maxProfit(prices) {
// 第i天状态 持股 卖出 非冷冻期(不持股) 处于冷冻期
const dp = new Array(prices.length).fill(0).map(() => [0, 0, 0, 0]);
dp[0][0] = -prices[0];
for (let i = 1; i < prices.length; i++) {
// 持股
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2] - prices[i]);
// 卖出
dp[i][1] = dp[i - 1][0] + prices[i];
// 非冷冻期(不持股)
dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1]);
// 冷冻期(上一天卖出)
dp[i][3] = dp[i - 1][1];
}
return Math.max(...dp.pop());
};
```
```javascript
const maxProfit = (prices) => {
if(prices.length < 2) {