mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Update 0121.卖股票的最佳时机.md 贪心以及动态规划 Go版本
This commit is contained in:
@ -311,7 +311,36 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
> 贪心法:
|
||||||
|
```Go
|
||||||
|
func maxProfit(prices []int) int {
|
||||||
|
low := math.MaxInt32
|
||||||
|
rlt := 0
|
||||||
|
for i := range prices{
|
||||||
|
low = min(low, prices[i])
|
||||||
|
rlt = max(rlt, prices[i]-low)
|
||||||
|
}
|
||||||
|
|
||||||
|
return rlt
|
||||||
|
}
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a < b{
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a, b int) int {
|
||||||
|
if a > b{
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 动态规划:版本一
|
||||||
```Go
|
```Go
|
||||||
func maxProfit(prices []int) int {
|
func maxProfit(prices []int) int {
|
||||||
length:=len(prices)
|
length:=len(prices)
|
||||||
@ -338,6 +367,29 @@ func max(a,b int)int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 动态规划:版本二
|
||||||
|
```Go
|
||||||
|
func maxProfit(prices []int) int {
|
||||||
|
dp := [2][2]int{}
|
||||||
|
dp[0][0] = -prices[0]
|
||||||
|
dp[0][1] = 0
|
||||||
|
for i := 1; i < len(prices); i++{
|
||||||
|
dp[i%2][0] = max(dp[(i-1)%2][0], -prices[i])
|
||||||
|
dp[i%2][1] = max(dp[(i-1)%2][1], dp[(i-1)%2][0]+prices[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
return dp[(len(prices)-1)%2][1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a, b int) int {
|
||||||
|
if a > b{
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
JavaScript:
|
JavaScript:
|
||||||
|
|
||||||
> 动态规划
|
> 动态规划
|
||||||
|
Reference in New Issue
Block a user