最大子数组:数组中子序列和最大的子数组的和求解
1.分治法:将问题的分割分成三部分进行考虑leftsum,rightsum和crosssum进行综合考虑
分治法代码:
#include"iostream"
#include"cstdio"
using namespace std;
int a[] = {0, 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
int length=0;
int sum=0;
int inf=-99999999;
int maxcross(int left,int mid,int right)
{
int leftsum=inf;
int rightsum=inf;
int sum=0;
for(int i=mid;i>=left;i--)
{
sum+=a[i];
if(sum>leftsum) leftsum=sum;
}
sum=0;
for(int j=mid+1;j<=right;j++)
{
sum+=a[j];
if(sum>rightsum) rightsum=sum;
}
return leftsum+rightsum;
}
int maxsub(int left,int right)
{
int mid=(left+right)/2;
if(left==right) return a[left];
else
{
int leftsum=0,rightsum=0,crosssum=0;
leftsum=maxsub(left,mid);
rightsum=maxsub(mid+1,right);
crosssum=maxcross(left,mid,right);
if(leftsum>=rightsum&&leftsum>=crosssum) return leftsum;
else
{
if(rightsum>=leftsum&&rightsum>=crosssum) return rightsum;
else return crosssum;
}
}
}
int main()
{
length=sizeof(a)/sizeof(int);
cout<<maxsub(1,length-1)<<endl;
return 0;
}
2.动态规划
思想和考虑:
状态:dp[i]用来记录以a[i]结尾的子数组中最大的数组和
有两种情况:
当dp[i-1]>=0时dp[i]=dp[i-1]+a[i];
当dp[i-1]<0时,dp[i]=a[i];
上述就是状态转移方程。
最后我们从dp[i]中选取最大的就是要求得值
talk is cheap,show me the code
#include"iostream"
#include"cstdio"
using namespace std;
int a[] = {0, 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
int length=0;
int sum=0;
int dp[100];
int main()
{
length=sizeof(a)/sizeof(int);
for(int i=1;i<=length-1;i++)
{
dp[i]=1;
if(dp[i-1]<0) dp[i]=a[i];
else dp[i]=dp[i-1]+a[i];
if(sum<dp[i]) sum=dp[i];
}
cout<<sum<<endl;
return 0;
}
很显然,虽然动态规划相比分治法要更好实现,并且思路更为简洁