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 10b633a

Browse files
Merge pull request youngyangyang04#1224 from liumingzhuo/master
Update 0121.卖股票的最佳时机.md 贪心以及动态规划解法 Go版本
2 parents dbdbf65 + 0e1cbda commit 10b633a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎problems/0121.买卖股票的最佳时机.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,36 @@ class Solution:
311311
```
312312

313313
Go:
314+
> 贪心法:
315+
```Go
316+
func maxProfit(prices []int) int {
317+
low := math.MaxInt32
318+
rlt := 0
319+
for i := range prices{
320+
low = min(low, prices[i])
321+
rlt = max(rlt, prices[i]-low)
322+
}
323+
324+
return rlt
325+
}
326+
func min(a, b int) int {
327+
if a < b{
328+
return a
329+
}
330+
331+
return b
332+
}
333+
334+
func max(a, b int) int {
335+
if a > b{
336+
return a
337+
}
338+
339+
return b
340+
}
341+
```
314342
343+
> 动态规划:版本一
315344
```Go
316345
func maxProfit(prices []int) int {
317346
length:=len(prices)
@@ -338,6 +367,29 @@ func max(a,b int)int {
338367
}
339368
```
340369

370+
> 动态规划:版本二
371+
```Go
372+
func maxProfit(prices []int) int {
373+
dp := [2][2]int{}
374+
dp[0][0] = -prices[0]
375+
dp[0][1] = 0
376+
for i := 1; i < len(prices); i++{
377+
dp[i%2][0] = max(dp[(i-1)%2][0], -prices[i])
378+
dp[i%2][1] = max(dp[(i-1)%2][1], dp[(i-1)%2][0]+prices[i])
379+
}
380+
381+
return dp[(len(prices)-1)%2][1]
382+
}
383+
384+
func max(a, b int) int {
385+
if a > b{
386+
return a
387+
}
388+
389+
return b
390+
}
391+
```
392+
341393
JavaScript:
342394

343395
> 动态规划

0 commit comments

Comments
(0)

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