File tree Expand file tree Collapse file tree 3 files changed +93
-0
lines changed Expand file tree Collapse file tree 3 files changed +93
-0
lines changed Original file line number Diff line number Diff line change @@ -200,6 +200,31 @@ class Solution:
200
200
201
201
Go:
202
202
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
+
203
228
Javascript:
204
229
``` javascript
205
230
// 方法一:动态规划(dp 数组)
Original file line number Diff line number Diff line change @@ -278,6 +278,38 @@ class Solution:
278
278
return dp[4]
279
279
```
280
280
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
+
281
313
JavaScript:
282
314
283
315
> 版本一:
Original file line number Diff line number Diff line change @@ -276,6 +276,42 @@ class Solution:
276
276
```
277
277
Go:
278
278
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
+
279
315
280
316
Javascript:
281
317
You can’t perform that action at this time.
0 commit comments