mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加(0122.买卖股票的最佳时机II动态规划.md):增加typescript版本
This commit is contained in:
@ -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;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user