diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 29242be3..2170dca3 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -275,6 +275,7 @@ const maxProfit = (prices) => { ### TypeScript: +贪心 ```typescript function maxProfit(prices: number[]): number { let resProfit: number = 0; @@ -285,6 +286,21 @@ function maxProfit(prices: number[]): number { }; ``` +动态规划 +```typescript +function maxProfit(prices: number[]): number { + const dp = Array(prices.length) + .fill(0) + .map(() => Array(2).fill(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][1] - prices[i]) + dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]) + } + return dp[prices.length - 1][1] +} +``` + ### Rust 贪心: