Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
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.
public class MaximumSubarray {
//求最大子列和的问题,本解用的是在线处理的方法,时间复杂度为O(n);
public static int MaximumSubarray4(int nums[]){
int MaxSum = nums[0];
int ThisSum = nums[0];
for (int i =1;i<nums.length;i++){ //这里的i要写成从1开始,否则当数组只有一个数的时候会出错
/* if (nums.length == 1){
MaxSum = nums[0];
break;
}*/
ThisSum +=nums[i];
//这里的主要想法是在线比较需要三个比较内容,一个是未加nums[i]的thisSum和加了nums[i]的thisSum,以及nums[i]这三个内容;
//比较加了nums[i]的thisSum,以及nums[i]
ThisSum = Math.max(ThisSum,nums[i]);
//比较未加nums[i]的thisSum和加了nums[i]的thisSum,括号中的MaxSum记录的就是未加nums[i]的thisSum的最大值
MaxSum = Math.max(ThisSum,MaxSum);
/*
这里是错误解法,此解法未考虑如果序列和都是负的情况
if(ThisSum > MaxSum) {
MaxSum = ThisSum;
}else if (ThisSum < 0&&MaxSum>0){
ThisSum = 0;
}*/
}
return MaxSum;
}
public static void main(String[] args) {
//int nums[] ={-2,1,-3,4,-1,2,1,-5,4};
//int nums[] = {-2,-1};
int nums[] = {-3,-2,0,-1};
int result = MaximumSubarray4(nums);
System.out.println(result);
}
}