子数组的最大和
方法1:
public static int max(int [] a){
int max = 0;
int b = 0;
for (int i=0;i<a.length;i++){
if (b<0)
b= a[i];
else
b+=a[i];
if (max<b)
max = b;
}
return max;
}
方法2:
public int maxSubsum(int[] a){
int[] b = new int[a.length+1];
for (int i=0;i<a.length+1;i++)
b[i]=0;
for (int i=0;i<a.length;i++){
for (int j= i;j<a.length;j++)
if (b[i+1]<b[i]+a[i])
b[i+1]=b[i]+a[i];//b[i]记录 任意j到i的最大和
}
int max = 0;
for (int i=0;i<a.length+1;i++){
if (b[i]>max)
max = b[i];
}
// System.out.println(max);
// i j max
// i j+1 < max
// i-1 j < max
return max;
}