题目:
输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为0(n).
{1,-2,3,10,-4,7,2,-1}
初始化数组中的每个数字,从第一个数字开始累加,如果开始时累加的结果小于0;从后面开始截取。累加并持续更新最大数组和
package helen.b;
public class MaxSum {
public static void main(String[] args) {
int a[]={-2,-2,-3,-10,-1,-7,-2};
int a1[]={1,-2,3,10,-4,7,2,-1};
System.out.println(maxSumArray(a));
System.out.println(maxSumArray(a1));
System.out.println(maxSumArray(null));
}
private static int maxSumArray(int[] a) {
if(a==null||a.length==0){
throw new RuntimeException();
}
int sum=a[0];
int tem=a[0];
for(int i=1;i<a.length;i++){
if(tem<0){
tem=a[i];
}else {
tem=tem+a[i];
}
if(tem>sum){
sum=tem;
}
}
return sum;
}
}