添加(0122.买卖股票的最佳时机II动态规划.md):增加typescript版本

This commit is contained in:
Steve2020
2022-05-12 16:40:54 +08:00
parent 3d1ed65088
commit 8ba775d04a

View File

@ -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;
};
```
-----------------------