Skip to content

Commit

Permalink
添加(0122.买卖股票的最佳时机II动态规划.md):增加typescript版本
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaofei-2020 committed May 12, 2022
1 parent 3d1ed65 commit 8ba775d
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions problems/0122.买卖股票的最佳时机II(动态规划).md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,42 @@ const maxProfit = (prices) => {
}
```

TypeScript:

> 动态规划

```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 第i天持有股票
dp[i][1]: 第i天不持有股票
*/
const length: number = prices.length;
if (length === 0) return 0;
const dp: number[][] = new Array(length).fill(0).map(_ => []);
dp[0] = [-prices[0], 0];
for (let i = 1; i < length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[length - 1][1];
};
```
> 贪心法
```typescript
function maxProfit(prices: number[]): number {
let resProfit: number = 0;
for (let i = 1, length = prices.length; i < length; i++) {
if (prices[i] > prices[i - 1]) {
resProfit += prices[i] - prices[i - 1];
}
}
return resProfit;
};
```



-----------------------
Expand Down

0 comments on commit 8ba775d

Please sign in to comment.