Problem
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
Example
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
More practice
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solution
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int max = nums[0], sum = max;
for (int i = 1; i < nums.length; i++) {
if (sum < 0) {
sum = nums[i];
} else {
sum += nums[i];
}
max = Math.max(max, sum);
}
return max;
}
}
DP
class Solution {
public int maxSubArray(int[] nums) {
int sum = nums[0], n = nums.length;
int[] dp = new int[n];
dp[0] = sum;
for (int i = 1; i < n; i++) {
if (sum < 0) sum = nums[i];
else sum += nums[i];
dp[i] = Math.max(dp[i-1], sum);
}
return dp[n-1];
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。