Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1fae0b0

Browse files
committed
docs: add No53 题解
1 parent bf531a7 commit 1fae0b0

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# No.53 最大子序和
2+
3+
难度:`easy`
4+
5+
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
6+
7+
## 示例
8+
9+
10+
11+
示例:
12+
```
13+
输入: [-2,1,-3,4,-1,2,1,-5,4],
14+
输出: 6
15+
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
16+
```
17+
18+
## 进阶
19+
20+
进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
21+
22+
## 解题思路
23+
24+
**思路一:**
25+
26+
暴力法,双重循环,每次遍历求和并保留最大值。
27+
28+
代码如下:
29+
30+
```javascript
31+
/**
32+
* @param {number[]} nums
33+
* @return {number}
34+
*/
35+
var maxSubArray = function(nums) {
36+
//暴力法
37+
let max = -Infinity;
38+
for (let i = 0, n = nums.length; i < n; i++) {
39+
let total = 0;
40+
for (let j = i; j < n; j++) {
41+
total += nums[j];
42+
if (total > max)
43+
max = total;
44+
}
45+
}
46+
return max;
47+
};
48+
```
49+
50+
**思路二:**
51+
52+
动态规划,一遍遍历,每次遍历计算出。类似寻找最大最小值的题目,初始值一定要定义成理论上的最小最大值

0 commit comments

Comments
 (0)