题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18
解法比较简单,直接代码:
public class MaxsubArray {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int list[] = {-1, -1, -1, 10, -1, 5, -1, -1};
int max = getmaxsub(list);
System.out.println(max);
}
public static int getmaxsub(int a[]) {
int sum;//当前位置的和
int max;//目前为止最大的子数组和
int left,right;//子数组的位置
int t1;//子数组的临时左位置
//初始化
sum=max=a[0];
left=right=t1=0;
for(int i=1;i<a.length;i++){
sum+=a[i];
if(sum<0){
sum=0;//如果和为负了,就应该重新计算
t1=i+1;//t1也从下一个位置开始
continue;
}
if(sum>max){//如果当前和比原先的最大值还大
max=sum;//最大值等于当前值
left=t1;//左右区间也要调成相应的
right=i;
}
}
for(int i=left;i<=right;i++){
System.out.println(a[i]);
}
return max;
}
}