diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index f3e7541b..f037fe85 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -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]); +}; +``` + + + -----------------------