Skip to content

Commit 35154b7

Browse files
committed
增加买卖股票最佳时机Ⅱ,买卖股票最佳时机Ⅲ,买卖股票最佳时机Ⅳ go版本
1 parent 99d28fc commit 35154b7

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed

problems/0122.买卖股票的最佳时机II(动态规划).md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,31 @@ class Solution:
200200

201201
Go:
202202

203+
```go
204+
func maxProfit(prices []int) int {
205+
//创建数组
206+
dp:=make([][]int,len(prices))
207+
for i:=0;i<len(prices);i++{
208+
dp[i]=make([]int,2)
209+
}
210+
dp[0][0]=-prices[0]
211+
dp[0][1]=0
212+
for i:=1;i<len(prices);i++{
213+
dp[i][0]=max(dp[i-1][0],dp[i-1][1]-prices[i])
214+
dp[i][1]=max(dp[i-1][1],dp[i-1][0]+prices[i])
215+
}
216+
return dp[len(prices)-1][1]
217+
}
218+
func max(a,b int)int{
219+
if a<b{
220+
return b
221+
}
222+
return a
223+
}
224+
```
225+
226+
227+
203228
Javascript:
204229
```javascript
205230
// 方法一:动态规划(dp 数组)

problems/0123.买卖股票的最佳时机III.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,38 @@ class Solution:
278278
return dp[4]
279279
```
280280

281+
Go:
282+
283+
```go
284+
func maxProfit(prices []int) int {
285+
dp:=make([][]int,len(prices))
286+
for i:=0;i<len(prices);i++{
287+
dp[i]=make([]int,5)
288+
}
289+
dp[0][0]=0
290+
dp[0][1]=-prices[0]
291+
dp[0][2]=0
292+
dp[0][3]=-prices[0]
293+
dp[0][4]=0
294+
for i:=1;i<len(prices);i++{
295+
dp[i][0]=dp[i-1][0]
296+
dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i])
297+
dp[i][2]=max(dp[i-1][2],dp[i-1][1]+prices[i])
298+
dp[i][3]=max(dp[i-1][3],dp[i-1][2]-prices[i])
299+
dp[i][4]=max(dp[i-1][4],dp[i-1][3]+prices[i])
300+
}
301+
return dp[len(prices)-1][4]
302+
}
303+
func max(a,b int)int{
304+
if a>b{
305+
return a
306+
}
307+
return b
308+
}
309+
```
310+
311+
312+
281313
JavaScript:
282314

283315
> 版本一:

problems/0188.买卖股票的最佳时机IV.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,42 @@ class Solution:
276276
```
277277
Go:
278278

279+
```go
280+
func maxProfit(k int, prices []int) int {
281+
if len(prices)==0{
282+
return 0
283+
}
284+
dp:=make([][]int,len(prices))
285+
for i:=0;i<len(prices);i++{
286+
dp[i]=make([]int,2*k+1)
287+
}
288+
for i:=1;i<len(dp[0]);i++{
289+
if i%2!=0{
290+
dp[0][i]=-prices[0]
291+
}
292+
}
293+
for i:=1;i<len(prices);i++{
294+
dp[i][0]=dp[i-1][0]
295+
for j:=1;j<len(dp[0]);j++{
296+
if j%2!=0{
297+
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]-prices[i])
298+
}else {
299+
dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]+prices[i])
300+
}
301+
}
302+
}
303+
return dp[len(prices)-1][2*k]
304+
}
305+
func max(a,b int)int{
306+
if a>b{
307+
return a
308+
}
309+
return b
310+
}
311+
```
312+
313+
314+
279315

280316
Javascript:
281317

0 commit comments

Comments
 (0)