Merge pull request #1323 from xiaofei-2020/dp37

添加(0309.最佳买卖股票时机含冷冻期.md):增加typescript版本
This commit is contained in:
程序员Carl
2022-06-02 08:38:58 +08:00
committed by GitHub

View File

@ -325,6 +325,66 @@ const maxProfit = (prices) => {
};
```
TypeScript
> 版本一,与本文思路一致
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 持股状态;
dp[i][1]: 无股状态,当天为非冷冻期;
dp[i][2]: 无股状态,当天卖出;
dp[i][3]: 无股状态,当天为冷冻期;
*/
const length: number = prices.length;
const dp: number[][] = new Array(length).fill(0).map(_ => []);
dp[0][0] = -prices[0];
dp[0][1] = dp[0][2] = dp[0][3] = 0;
for (let i = 1; i < 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];
}
const lastEl: number[] = dp[length - 1];
return Math.max(lastEl[1], lastEl[2], lastEl[3]);
};
```
> 版本二,状态定义略有不同,可以帮助理解
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 持股状态,当天买入;
dp[i][1]: 持股状态,当天未买入;
dp[i][2]: 无股状态,当天卖出;
dp[i][3]: 无股状态,当天未卖出;
买入有冷冻期限制,其实就是状态[0]只能由前一天的状态[3]得到;
如果卖出有冷冻期限制,其实就是[2]由[1]得到。
*/
const length: number = prices.length;
const dp: number[][] = new Array(length).fill(0).map(_ => []);
dp[0][0] = -prices[0];
dp[0][1] = -Infinity;
dp[0][2] = dp[0][3] = 0;
for (let i = 1; i < length; i++) {
dp[i][0] = dp[i - 1][3] - prices[i];
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0]);
dp[i][2] = Math.max(dp[i - 1][0], dp[i - 1][1]) + prices[i];
dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2]);
}
return Math.max(dp[length - 1][2], dp[length - 1][3]);
};
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>