Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4a831be

Browse files
Merge pull request youngyangyang04#2612 from Monster-XU-jesus/master
Update 121. 买卖股票的最佳时机.md
2 parents 186cb53 + afbcb1d commit 4a831be

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

‎problems/0121.买卖股票的最佳时机.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ function maxProfit(prices: number[]): number {
466466
};
467467
```
468468

469-
> 动态规划
469+
> 动态规划:版本一
470470
471471
```typescript
472472
function maxProfit(prices: number[]): number {
@@ -487,6 +487,26 @@ function maxProfit(prices: number[]): number {
487487
};
488488
```
489489

490+
> 动态规划:版本二
491+
492+
```typescript
493+
// dp[i][0] 表示第i天持有股票所得最多现金
494+
// dp[i][1] 表示第i天不持有股票所得最多现金
495+
function maxProfit(prices: number[]): number {
496+
const dp:number[][] = Array(2).fill(0).map(item => Array(2));
497+
dp[0][0] = -prices[0];
498+
dp[0][1] = 0;
499+
500+
for (let i = 1; i < prices.length; i++) {
501+
dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], -prices[i]);
502+
dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]);
503+
}
504+
505+
// 返回不持有股票的最大现金
506+
return dp[(prices.length-1) % 2][1];
507+
};
508+
```
509+
490510
### C#:
491511

492512
> 贪心法

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /