Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c8ecb49

Browse files
Merge pull request youngyangyang04#2786 from markwang1992/122-maxProfit
122.买卖股票的最佳时机II增加Go动态规划滚动数组版本
2 parents 1bc6338 + 5523957 commit c8ecb49

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,27 @@ func max(a, b int) int {
251251
}
252252
```
253253

254+
```go
255+
// 动态规划 版本二 滚动数组
256+
func maxProfit(prices []int) int {
257+
dp := [2][2]int{} // 注意这里只开辟了一个2 * 2大小的二维数组
258+
dp[0][0] = -prices[0]
259+
dp[0][1] = 0
260+
for i := 1; i < len(prices); i++ {
261+
dp[i%2][0] = max(dp[(i-1)%2][0], dp[(i - 1) % 2][1] - prices[i])
262+
dp[i%2][1] = max(dp[(i-1)%2][1], dp[(i-1)%2][0] + prices[i])
263+
}
264+
return dp[(len(prices)-1)%2][1]
265+
}
266+
267+
func max(x, y int) int {
268+
if x > y {
269+
return x
270+
}
271+
return y
272+
}
273+
```
274+
254275
### JavaScript:
255276

256277
```javascript

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /