diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 5a165a14..12b21fde 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -295,6 +295,42 @@ const maxProfit = (prices) => { } ``` +TypeScript: + +> 动态规划 + +```typescript +function maxProfit(prices: number[]): number { + /** + dp[i][0]: 第i天持有股票 + dp[i][1]: 第i天不持有股票 + */ + const length: number = prices.length; + if (length === 0) return 0; + const dp: number[][] = new Array(length).fill(0).map(_ => []); + dp[0] = [-prices[0], 0]; + for (let i = 1; i < 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[length - 1][1]; +}; +``` + +> 贪心法 + +```typescript +function maxProfit(prices: number[]): number { + let resProfit: number = 0; + for (let i = 1, length = prices.length; i < length; i++) { + if (prices[i] > prices[i - 1]) { + resProfit += prices[i] - prices[i - 1]; + } + } + return resProfit; +}; +``` + -----------------------