8000 feat: [贪心] 53 · chenshiwei-io/leetcode@8405b9a · GitHub
[go: up one dir, main page]

Skip to content

Commit 8405b9a

Browse files
author
chen-shiwei
committed
feat: [贪心] 53
1 parent 001c24a commit 8405b9a

File tree

3 files changed

+78
-23
lines changed

3 files changed

+78
-23
lines changed

leetcode/53.最大子序和/maxSubArray.go

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package _3_最大子序和_贪心_dp
2+
3+
import "math"
4+
5+
func maxSubArray(nums []int) int {
6+
l := len(nums)
7+
var maxN = nums[0]
8+
for i := 1; i < l; i++ {
9+
if nums[i]+nums[i-1] > nums[i] {
10+
nums[i] += nums[i-1]
11+
}
12+
maxN = max(nums[i], maxN)
13+
}
14+
return maxN
15+
}
16+
17+
func maxSubArrayWithDP(nums []int) int {
18+
l := len(nums)
19+
20+
var dp = make([]int, l)
21+
dp[0] = nums[0]
22+
var ans int
23+
for i := 1; i < l; i++ {
24+
if nums[i]+nums[i-1] > nums[i] {
25+
nums[i] = nums[i] + nums[i-1]
26+
}
27+
if nums[i] > ans {
28+
ans = nums[i]
29+
}
30+
}
31+
32+
return ans
33+
}
34+
35+
func maxSubArrayWithGreedy(nums []int) int {
36+
l := len(nums)
37+
38+
var ans int
39+
var result = math.MinInt32
40+
for i := 0; i < l; i++ {
41+
ans += nums[i]
42+
if ans > result {
43+
result = ans
44+
}
45+
46+
if ans < 0 {
47+
ans = 0
48+
}
49+
}
50+
51+
return result
52+
}
53+
54+
func maxSubArrayWithFor(nums []int) int {
55+
l := len(nums)
56+
var ans = math.MinInt32
57+
for i := 0; i < l; i++ {
58+
var tmp int
59+
for j := i; j < l; j++ {
60+
tmp += nums[j]
61+
if tmp > ans {
62+
ans = tmp
63+
}
64+
}
65+
}
66+
67+
return ans
68+
}
69+
70+
func max(a, b int) int {
71+
if a >= b {
72+
return a
73+
}
74+
75+
return b
76+
}

leetcode/53.最大子序和/maxSubArray_test.go renamed to leetcode/53.最大子序和_贪心_dp/maxSubArray_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package _3_最大子序和
1+
package _3_最大子序和_贪心_dp
22

33
import "testing"
44

@@ -17,7 +17,7 @@ func Test_maxSubArray(t *testing.T) {
1717
}
1818
for _, tt := range tests {
1919
t.Run(tt.name, func(t *testing.T) {
20-
if got := maxSubArray(tt.args.nums); got != tt.want {
20+
if got := maxSubArrayWithGreedy(tt.args.nums); got != tt.want {
2121
t.Errorf("maxSubArray() = %v, want %v", got, tt.want)
2222
}
2323
})

0 commit comments

Comments
 (0)
0