最长子数组,即数组元素和最大的子数组,方法如下:
1.分治 将数组一分为二,则该最长数组有三种情况:1.在左子数组中,2.在右子数组中 3.跨越中间节点的子数组
递归地解决该问题,代码如下:
int add(int a[],int fro,int re){
if(fro==re)
return a[fro];
int mid=(fro+re)/2;
int max1=add(a,fro,mid);
int max2=add(a,mid+1,re);
int temp=a[mid],max3=a[mid];
for(int i=mid-1;i>=fro;i--){
temp+=a[i];
if(temp>max3)
max3=temp;
}
temp=max3;
for(int i=mid+1;i<=re;++i){
temp+=a[i];
if(temp>max3)
max3=temp;
}
if(max1>max2){
return max1>max3?max1:max3;
}
else return max2>max3?max2:max3;
}
2.动态规划
遍历整个数组,设以i为结尾的数组最大子数组长度为s,则以i+1为结尾的最大子数组长度=max(s+a[i+1],a[i+1]),这取决于s是否>0,再用max变量存储最大值,代码如下:
int max(int a,int b){
return a>b?a:b;
}
int add(int a[],int n){
int sum=a[0],temp=a[0];
for(i=1;i<n;++i){
temp=max(temp+a[i],a[i]);
sum=max(temp,sum);
}
return sum;
}