问题:数组
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.app
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
.ide
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.spa
解决:code
①使用时间复杂度为O(n)的方法解决(耗时16ms),属于一种DP问题:递归
最大连续子串问题,对于一个元素数为n的数组,其含有2^n个子序列和n(n+1)/2个子串。若是使用穷举法,则至少须要O(n^2)的时间才能获得答案。所以采用Jay Kadane 提出的线性时间的最优解法:it
【注意】io
public class Solution {
public int maxSubArray(int[] nums) {
int sum = 0;
int max = Integer.MIN_VALUE;//若令max的值为0,会致使数组元素全部的和都为0的时候返回错误
for (int i = 0;i < nums.length ;i ++ ) {
sum += nums[i];
if(max < sum){
max = sum;
}
if (sum <= 0) {
sum = 0;
}
}
return max;
}
}ast
public class Solution {
public int maxSubArray(int[] nums) {
int sum = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++) {
sum = nums[i] + Math.max(sum, 0);
max = Math.max(sum, max);
}
return max;
}
} //13ms
②另外题目要求也能够采用分治法(递归)Divide and Conquer Approach解决该问题,时间复杂度为O(nlgn)。分治法的思想就相似于二分搜索法,咱们须要把数组一分为二,分别找出左边和右边的最大子数组之和,而后还要从中间开始向左右分别扫描,求出的最大值分别和左右两边得出的最大值相比较取最大的那一个。耗时23ms,性能不是很好。
public class Solution { public int maxSubArray(int[] nums) { if (nums.length == 0) { return 0; } return divide(nums,0,nums.length - 1); } public int divide(int[] nums,int left,int right){ if (left >= right) {//若未写=会提示数组下标越界 return nums[left]; } int mid = (right - left) / 2 + left; int lmax = divide(nums,left,mid - 1); int rmax = divide(nums,mid + 1,right); int mmax = nums[mid];//初始值为中间值 int sum = mmax; for (int i = mid - 1;i >= left ;i -- ) {//扫描左半部分 sum += nums[i]; mmax = Math.max(mmax,sum); } sum = mmax; for (int i = mid + 1;i <= right ;i ++ ) {//扫描右半部份 sum += nums[i]; mmax = Math.max(mmax,sum); } return Math.max(mmax,Math.max(lmax,rmax)); } }