Skip to content

Commit feef02a

Browse files
Merge pull request youngyangyang04#1317 from xiaofei-2020/dp35
添加(0123.买卖股票的最佳时机III.md):增加typescript版本
2 parents f662f5e + a71f7d2 commit feef02a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

problems/0123.买卖股票的最佳时机III.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,36 @@ const maxProfit = prices => {
352352
};
353353
```
354354

355+
TypeScript:
356+
357+
> 版本一
358+
359+
```typescript
360+
function maxProfit(prices: number[]): number {
361+
/**
362+
dp[i][0]: 无操作;
363+
dp[i][1]: 第一次买入;
364+
dp[i][2]: 第一次卖出;
365+
dp[i][3]: 第二次买入;
366+
dp[i][4]: 第二次卖出;
367+
*/
368+
const length: number = prices.length;
369+
if (length === 0) return 0;
370+
const dp: number[][] = new Array(length).fill(0)
371+
.map(_ => new Array(5).fill(0));
372+
dp[0][1] = -prices[0];
373+
dp[0][3] = -prices[0];
374+
for (let i = 1; i < length; i++) {
375+
dp[i][0] = dp[i - 1][0];
376+
dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
377+
dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
378+
dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
379+
dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
380+
}
381+
return Math.max(dp[length - 1][2], dp[length - 1][4]);
382+
};
383+
```
384+
355385
Go:
356386

357387
> 版本一:

0 commit comments

Comments
 (0)