mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1257 from xiaofei-2020/greed23
添加(0714.买卖股票的最佳时机含手续费.md):增加typescript版本
This commit is contained in:
@ -293,6 +293,50 @@ var maxProfit = function(prices, fee) {
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
> 贪心
|
||||
|
||||
```typescript
|
||||
function maxProfit(prices: number[], fee: number): number {
|
||||
if (prices.length === 0) return 0;
|
||||
let minPrice: number = prices[0];
|
||||
let profit: number = 0;
|
||||
for (let i = 1, length = prices.length; i < length; i++) {
|
||||
if (minPrice > prices[i]) {
|
||||
minPrice = prices[i];
|
||||
}
|
||||
if (minPrice + fee < prices[i]) {
|
||||
profit += prices[i] - minPrice - fee;
|
||||
minPrice = prices[i] - fee;
|
||||
}
|
||||
}
|
||||
return profit;
|
||||
};
|
||||
```
|
||||
|
||||
> 动态规划
|
||||
|
||||
```typescript
|
||||
function maxProfit(prices: number[], fee: number): number {
|
||||
/**
|
||||
dp[i][1]: 第i天不持有股票的最大所剩现金
|
||||
dp[i][0]: 第i天持有股票的最大所剩现金
|
||||
*/
|
||||
const length: number = prices.length;
|
||||
const dp: number[][] = new Array(length).fill(0).map(_ => []);
|
||||
dp[0][1] = 0;
|
||||
dp[0][0] = -prices[0];
|
||||
for (let i = 1, length = prices.length; i < length; i++) {
|
||||
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
|
||||
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
|
||||
}
|
||||
return Math.max(dp[length - 1][0], dp[length - 1][1]);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user