Skip to content

Commit

Permalink
新增 0123.买卖股票的最佳时机III.md Go解法
Browse files Browse the repository at this point in the history
  • Loading branch information
RyouMon committed Nov 6, 2021
1 parent 36a4a90 commit 5483a71
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions problems/0123.买卖股票的最佳时机III.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,38 @@ const maxProfit = prices => {
};
```

Go:

> 版本一:
```go
// 买卖股票的最佳时机III 动态规划
// 时间复杂度O(n) 空间复杂度O(n)
func maxProfit(prices []int) int {
dp := make([][]int, len(prices))
status := make([]int, len(prices) * 4)
for i := range dp {
dp[i] = status[:4]
status = status[4:]
}
dp[0][0], dp[0][2] = -prices[0], -prices[0]

for i := 1; i < len(prices); i++ {
dp[i][0] = max(dp[i - 1][0], -prices[i])
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] - prices[i])
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] + prices[i])
}

return dp[len(prices) - 1][3]
}

func max(a, b int) int {
if a > b {
return a
}
return b
}
```


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

0 comments on commit 5483a71

Please sign in to comment.