File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -426,6 +426,46 @@ var maxProfit = function(prices) {
426
426
};
427
427
```
428
428
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
+
429
469
430
470
-----------------------
431
471
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
You can’t perform that action at this time.
0 commit comments