diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index e9aea0e6..df586ff9 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -466,7 +466,7 @@ function maxProfit(prices: number[]): number { }; ``` -> 动态规划 +> 动态规划:版本一 ```typescript function maxProfit(prices: number[]): number { @@ -487,6 +487,26 @@ function maxProfit(prices: number[]): number { }; ``` +> 动态规划:版本二 + +```typescript +// dp[i][0] 表示第i天持有股票所得最多现金 +// dp[i][1] 表示第i天不持有股票所得最多现金 +function maxProfit(prices: number[]): number { + const dp:number[][] = Array(2).fill(0).map(item => Array(2)); + dp[0][0] = -prices[0]; + dp[0][1] = 0; + + for (let i = 1; i < prices.length; i++) { + dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], -prices[i]); + dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]); + } + + // 返回不持有股票的最大现金 + return dp[(prices.length-1) % 2][1]; +}; +``` + ### C#: > 贪心法