mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
新增 0714.买卖股票的最佳时机含手续费(动态规划).md Go解法
This commit is contained in:
@ -152,6 +152,37 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
```go
|
||||||
|
// 买卖股票的最佳时机含手续费 动态规划
|
||||||
|
// 时间复杂度O(n) 空间复杂度O(n)
|
||||||
|
func maxProfit(prices []int, fee int) int {
|
||||||
|
if len(prices) == 1 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
dp := make([][]int, len(prices))
|
||||||
|
status := make([]int, len(prices) * 2)
|
||||||
|
for i := range dp {
|
||||||
|
dp[i] = status[:2]
|
||||||
|
status = status[2:]
|
||||||
|
}
|
||||||
|
dp[0][0] = -prices[0]
|
||||||
|
|
||||||
|
for i := 1; i < len(dp); i++ {
|
||||||
|
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
|
||||||
|
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee)
|
||||||
|
}
|
||||||
|
|
||||||
|
return dp[len(dp) - 1][1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a, b int) int {
|
||||||
|
if a > b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Javascript:
|
Javascript:
|
||||||
```javascript
|
```javascript
|
||||||
|
Reference in New Issue
Block a user