File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -295,6 +295,42 @@ const maxProfit = (prices) => {
295295}
296296```
297297
298+ TypeScript:
299+
300+ > 动态规划
301+
302+ ```typescript
303+ function maxProfit (prices: number[ ] ): number {
304+ /**
305+ dp[ i] [ 0 ] : 第i天持有股票
306+ dp[ i] [ 1 ] : 第i天不持有股票
307+ * /
308+ const length: number = prices.length;
309+ if (length === 0) return 0;
310+ const dp: number[ ] [ ] = new Array(length).fill(0).map(_ => [ ] );
311+ dp[ 0] = [ -prices[ 0] , 0] ;
312+ for (let i = 1; i < length; i++) {
313+ dp[ i] [ 0 ] = Math.max(dp[ i - 1] [ 0 ] , dp[ i - 1] [ 1 ] - prices[ i] );
314+ dp[ i] [ 1 ] = Math.max(dp[ i - 1] [ 1 ] , dp[ i - 1] [ 0 ] + prices[ i] );
315+ }
316+ return dp[ length - 1] [ 1 ] ;
317+ };
318+ ```
319+
320+ > 贪心法
321+
322+ ```typescript
323+ function maxProfit(prices: number[]): number {
324+ let resProfit: number = 0;
325+ for (let i = 1, length = prices.length; i < length; i++) {
326+ if (prices[i] > prices[i - 1]) {
327+ resProfit += prices[i] - prices[i - 1];
328+ }
329+ }
330+ return resProfit;
331+ };
332+ ```
333+
298334
299335
300336-----------------------
You can’t perform that action at this time.
0 commit comments