mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #866 from baici1/master
增加买卖股票最佳时机Ⅱ,买卖股票最佳时机Ⅲ,买卖股票最佳时机Ⅳ go版本
This commit is contained in:
@ -200,6 +200,31 @@ class Solution:
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
func maxProfit(prices []int) int {
|
||||
//创建数组
|
||||
dp:=make([][]int,len(prices))
|
||||
for i:=0;i<len(prices);i++{
|
||||
dp[i]=make([]int,2)
|
||||
}
|
||||
dp[0][0]=-prices[0]
|
||||
dp[0][1]=0
|
||||
for i:=1;i<len(prices);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])
|
||||
}
|
||||
return dp[len(prices)-1][1]
|
||||
}
|
||||
func max(a,b int)int{
|
||||
if a<b{
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
Javascript:
|
||||
```javascript
|
||||
// 方法一:动态规划(dp 数组)
|
||||
|
@ -278,6 +278,38 @@ class Solution:
|
||||
return dp[4]
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
func maxProfit(prices []int) int {
|
||||
dp:=make([][]int,len(prices))
|
||||
for i:=0;i<len(prices);i++{
|
||||
dp[i]=make([]int,5)
|
||||
}
|
||||
dp[0][0]=0
|
||||
dp[0][1]=-prices[0]
|
||||
dp[0][2]=0
|
||||
dp[0][3]=-prices[0]
|
||||
dp[0][4]=0
|
||||
for i:=1;i<len(prices);i++{
|
||||
dp[i][0]=dp[i-1][0]
|
||||
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])
|
||||
dp[i][4]=max(dp[i-1][4],dp[i-1][3]+prices[i])
|
||||
}
|
||||
return dp[len(prices)-1][4]
|
||||
}
|
||||
func max(a,b int)int{
|
||||
if a>b{
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
JavaScript:
|
||||
|
||||
> 版本一:
|
||||
|
@ -276,6 +276,42 @@ class Solution:
|
||||
```
|
||||
Go:
|
||||
|
||||
```go
|
||||
func maxProfit(k int, prices []int) int {
|
||||
if len(prices)==0{
|
||||
return 0
|
||||
}
|
||||
dp:=make([][]int,len(prices))
|
||||
for i:=0;i<len(prices);i++{
|
||||
dp[i]=make([]int,2*k+1)
|
||||
}
|
||||
for i:=1;i<len(dp[0]);i++{
|
||||
if i%2!=0{
|
||||
dp[0][i]=-prices[0]
|
||||
}
|
||||
}
|
||||
for i:=1;i<len(prices);i++{
|
||||
dp[i][0]=dp[i-1][0]
|
||||
for j:=1;j<len(dp[0]);j++{
|
||||
if j%2!=0{
|
||||
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]-prices[i])
|
||||
}else {
|
||||
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]+prices[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[len(prices)-1][2*k]
|
||||
}
|
||||
func max(a,b int)int{
|
||||
if a>b{
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
Javascript:
|
||||
|
||||
|
Reference in New Issue
Block a user