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 40457f0

Browse files
添加(0121.买卖股票的最佳时机.md):增加typescript版本
1 parent 3d1ed65 commit 40457f0

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,46 @@ var maxProfit = function(prices) {
426426
};
427427
```
428428

429+
TypeScript:
430+
431+
> 贪心法
432+
433+
```typescript
434+
function maxProfit(prices: number[]): number {
435+
if (prices.length === 0) return 0;
436+
let buy: number = prices[0];
437+
let profitMax: number = 0;
438+
for (let i = 1, length = prices.length; i < length; i++) {
439+
profitMax = Math.max(profitMax, prices[i] - buy);
440+
buy = Math.min(prices[i], buy);
441+
}
442+
return profitMax;
443+
};
444+
```
445+
446+
> 动态规划
447+
448+
```typescript
449+
function maxProfit(prices: number[]): number {
450+
/**
451+
dp[i][0]: 第i天持有股票的最大现金
452+
dp[i][1]: 第i天不持有股票的最大现金
453+
*/
454+
const length = prices.length;
455+
if (length === 0) return 0;
456+
const dp: number[][] = [];
457+
dp[0] = [-prices[0], 0];
458+
for (let i = 1; i < length; i++) {
459+
dp[i] = [];
460+
dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
461+
dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]);
462+
}
463+
return dp[length - 1][1];
464+
};
465+
```
466+
467+
468+
429469

430470
-----------------------
431471
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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