Skip to content

Commit 599413c

Browse files
Create 53. 最大子数组和.md
1 parent 964e0a2 commit 599413c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Prefix Sum/53. 最大子数组和.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#### 53. 最大子数组和
2+
3+
难度:中等
4+
5+
---
6+
7+
给你一个整数数组 `nums` ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
8+
9+
**子数组** 是数组中的一个连续部分。
10+
11+
**示例 1:**
12+
13+
```
14+
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
15+
输出:6
16+
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
17+
```
18+
19+
**示例 2:**
20+
21+
```
22+
输入:nums = [1]
23+
输出:1
24+
```
25+
26+
**示例 3:**
27+
28+
```
29+
输入:nums = [5,4,-1,7,8]
30+
输出:23
31+
```
32+
33+
**提示:**
34+
35+
* `1 <= nums.length <= 10^5`
36+
* `-10^4 <= nums[i] <= 10^4`
37+
38+
**进阶:** 如果你已经实现复杂度为 `O(n)` 的解法,尝试使用更为精妙的 **分治法** 求解。
39+
40+
---
41+
42+
前缀和:
43+
44+
顺序遍历并记录前缀和的最小值,与当前前缀和进行对比,取差值最大的即可。注意的是**前缀和数组长度为原数组长度 + 1**
45+
46+
```Java
47+
class Solution {
48+
public int maxSubArray(int[] nums) {
49+
int n = nums.length;
50+
int[] prefix = new int[n + 1];
51+
int current = 0, res = nums[0];
52+
for(int i = 1; i < n + 1; i++){
53+
prefix[i] = prefix[i - 1] + nums[i - 1];
54+
res = Math.max(res, prefix[i] - current);
55+
current = Math.min(current, prefix[i]);
56+
}
57+
return res;
58+
}
59+
}
60+
```

0 commit comments

Comments
 (0)