Skip to content

Commit b41676f

Browse files
committed
add 053
1 parent 946d035 commit b41676f

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
| :--: | :------------------------------------------ |
7676
| 70 | [Climbing Stairs][070] |
7777
| 121 | [Best Time to Buy and Sell Stock][121] |
78+
| 53 | [Maximum Subarray][053] |
7879

7980

8081
[leetcode]: https://leetcode.com/problemset/all/
@@ -116,3 +117,4 @@
116117
[278]: https://github.com/andavid/leetcode-java/blob/master/note/278/README.md
117118
[070]: https://github.com/andavid/leetcode-java/blob/master/note/070/README.md
118119
[121]: https://github.com/andavid/leetcode-java/blob/master/note/121/README.md
120+
[053]: https://github.com/andavid/leetcode-java/blob/master/note/053/README.md

note/053/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# [Maximum Subarray][title]
2+
3+
## Description
4+
5+
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
6+
7+
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
8+
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
9+
10+
**More practice:**
11+
12+
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+
可以从前往后扫描,假设 dp[i] 表示前 i 个元素的最大子序列和,如果 dp[i] < 0,那么 dp[i+1] 等于第 i+1 个元素的值,如果 dp[i] > 0,那么 dp[i+1] 等于 dp[i] 加上第 i+1 个元素的值,由此得到前 i+1 个元素的局部最大子序列和。和全局最大值进行比较,如果更大则进行更新。
18+
19+
## [完整代码][src]
20+
21+
```java
22+
class Solution {
23+
public int maxSubArray(int[] nums) {
24+
if (nums == null || nums.length == 0) return 0;
25+
26+
int sum = nums[0];
27+
int max = nums[0];
28+
29+
for (int i = 1; i < nums.length; i++) {
30+
sum = (sum < 0) ? nums[i] : (sum + nums[i]);
31+
if (sum > max) max = sum;
32+
}
33+
34+
return max;
35+
}
36+
}
37+
```
38+
39+
[title]: https://leetcode.com/problems/maximum-subarray
40+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_053/Solution.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int maxSubArray(int[] nums) {
3+
if (nums == null || nums.length == 0) return 0;
4+
5+
int sum = nums[0];
6+
int max = nums[0];
7+
8+
for (int i = 1; i < nums.length; i++) {
9+
sum = (sum < 0) ? nums[i] : (sum + nums[i]);
10+
if (sum > max) max = sum;
11+
}
12+
13+
return max;
14+
}
15+
16+
public static void main(String[] args) {
17+
Solution solution = new Solution();
18+
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
19+
System.out.println(solution.maxSubArray(nums));
20+
}
21+
}

0 commit comments

Comments
 (0)