Update 121. 买卖股票的最佳时机.md

This commit is contained in:
XZY
2024-07-15 12:14:43 +08:00
parent f26a95dbb1
commit afbcb1d98b

View File

@ -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#
> 贪心法