Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit ff1ed00

Browse files
committed
53 翻新
1 parent 7ab1d8a commit ff1ed00

File tree

3 files changed

+20
-38
lines changed

3 files changed

+20
-38
lines changed
+3-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
22

33
## 题目
4+
45
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
56

67
For example, given the array `[-2,1,-3,4,-1,2,1,-5,4]`,
@@ -10,11 +11,7 @@ the contiguous subarray `[4,-1,2,1]` has the largest sum = `6`.
1011
More practice:
1112

1213
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
13-
## 解题思路
14-
利用好`连续`这个约束
15-
16-
详见注释
17-
18-
## 总结
1914

15+
## 解题思路
2016

17+
利用好`连续`这个约束
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,27 @@
11
package problem0053
22

33
func maxSubArray(nums []int) int {
4-
l := len(nums)
4+
size := len(nums)
5+
tmp := nums[0]
6+
res := tmp
57

6-
if l == 0 {
7-
return 0
8-
}
9-
10-
if l == 1 {
11-
return nums[0]
12-
}
13-
14-
temp := nums[0]
15-
max := temp
16-
i := 1
17-
// 可以把 for 循环的过程,nums[:1] 每次增加一个,直到变成 nums 的过程。
18-
// temp 就是这个过程中,每个 nums[:i] 中的 max(nums[x:i]) (x=0,1,...,i-1)
19-
// 整个 nums 中连续子序列的最大值,就在 temp 的所有取值中
20-
for i < l {
21-
if temp < 0 {
22-
// 因为 连续性 的要求,而此时 temp < 0
23-
// temp 从 i 处重新开始
24-
temp = nums[i]
8+
for i := 1; i < size; i++ {
9+
// 题目要求是连续的子数组,假设 maxSum = sum(nums[i:k])
10+
// 可知必有 sum(nums[i:j]) >= 0 ,其中 i<j<k
11+
if tmp < 0 {
12+
tmp = nums[i]
2513
} else {
26-
temp += nums[i]
14+
tmp += nums[i]
2715
}
16+
res = max(res, tmp)
17+
}
2818

29-
if max < temp {
30-
max = temp
31-
}
19+
return res
20+
}
3221

33-
i++
22+
func max(a, b int) int {
23+
if a > b {
24+
return a
3425
}
35-
36-
return max
26+
return b
3727
}

Algorithms/0053.maximum-subarray/maximum-subarray_test.go

-5
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,6 @@ func Test_Problem0053(t *testing.T) {
3939
ans{-2},
4040
},
4141

42-
question{
43-
para{[]int{}},
44-
ans{0},
45-
},
46-
4742
// 如需多个测试,可以复制上方元素。
4843
}
4944

0 commit comments

Comments
 (0)