最大子数组求解 c++
#include<iostream>usingnamespacestd;voidMaxSubSum(int*arry,intlength);//线性时间算法求子数组最大和...
#include<iostream>
using namespace std;
void MaxSubSum(int *arry,int length);//线性时间算法求子数组最大和,联机算法。
int main(){
int a[]={0,2,4,-8,5,2,-1,2,-4,3};
MaxSubSum(a,10);
return 0;
}
void MaxSubSum(int *arry,int length)
{
int * head=arry;
int * end=arry;
int i,maxsum=0,cursum=0;
for(i=0;i<length;i++)
{
cursum+=arry[i];
if(cursum>maxsum)
{
maxsum = cursum;
end = &arry[i]; //end端点比较好确定 , head端点如何确定?
}
if(cursum<0)
{
cursum = 0;
}
}
cout<<"最大子数组为:";
while(head<=end)
{
cout<<*head<<" ";
head++;
}
cout<<"\n和为:"<<maxsum;
}
想输出最大子数组的每个数。 但head指针想不到怎么确定。 各位大神给点建议 展开
using namespace std;
void MaxSubSum(int *arry,int length);//线性时间算法求子数组最大和,联机算法。
int main(){
int a[]={0,2,4,-8,5,2,-1,2,-4,3};
MaxSubSum(a,10);
return 0;
}
void MaxSubSum(int *arry,int length)
{
int * head=arry;
int * end=arry;
int i,maxsum=0,cursum=0;
for(i=0;i<length;i++)
{
cursum+=arry[i];
if(cursum>maxsum)
{
maxsum = cursum;
end = &arry[i]; //end端点比较好确定 , head端点如何确定?
}
if(cursum<0)
{
cursum = 0;
}
}
cout<<"最大子数组为:";
while(head<=end)
{
cout<<*head<<" ";
head++;
}
cout<<"\n和为:"<<maxsum;
}
想输出最大子数组的每个数。 但head指针想不到怎么确定。 各位大神给点建议 展开
2个回答
展开全部
有一个想法 你可以试一下
由于maxsum是根据cursum来变的 所以head在计算cursum的时候就需要确定下来
而cursum又不一定是要求的 所以需要多一个变量保存cursum的head
于是代码改成
void MaxSubSum(int *arry,int length)
{
int * head=arry;
int * end=arry;
int * cur_head = arry;
int i,maxsum=0,cursum=0;
for(i=0;i<length;i++)
{
cursum+=arry[i];
if(cursum>maxsum)
{
maxsum = cursum;
end = &arry[i]; //end端点比较好确定 , head端点如何确定?
head = cur_head;
}
if(cursum<0)
{
cursum = 0;
cur_head = &array[i];
}
}
cout<<"最大子数组为:";
while(head<=end)
{
cout<<*head<<" ";
head++;
}
cout<<"\n和为:"<<maxsum;
}
不过个人认为你这个求最大的算法本身就有问题
应该改成
void MaxSubSum(int *arry,int length)
{
int * head=arry;
int * end=arry;
int * cur_head = arry;
int i,maxsum=0x80000000,cursum=0;
for(i=0;i<length;i++)
{
if(curSum <= 0)
{
curSum = data[i];
cur_head=&data[i];
}
else
curSum += data[i];
if(curSum > sum)
{
sum = curSum;
head = cur_head;
end=&data[i];
}
}
cout<<"最大子数组为:";
while(head<=end)
{
cout<<*head<<" ";
head++;
}
cout<<"\n和为:"<<maxsum;
}
你可以试试
更多追问追答
追问
没看出你所说的改算法是在哪改了。 其次{1,2,3,4,5,-16,17}发生越界问题。
追答
完整程序:
#include<iostream>
using namespace std;
void MaxSubSum(int *arry,int length);//线性时间算法求子数组最大和,联机算法。
int main(){
int a[]={1,2,3,4,5,-16,17};
MaxSubSum(a,sizeof a / sizeof(int));
return 0;
}
void MaxSubSum(int *arry,int length)
{
int * head=arry;
int * end=arry;
int * cur_head = arry;
int i,maxsum=0x80000000,curSum=0;
for(i=0;i<length;i++)
{
if(curSum <= 0)
{
curSum = arry[i];
cur_head=&arry[i];
}
else
curSum += arry[i];
if(curSum > maxsum)
{
maxsum = curSum;
head = cur_head;
end=&arry[i];
}
}
cout<<"最大子数组为:";
while(head<=end)
{
cout<<*head<<" ";
head++;
}
cout<<"\n和为:"<<maxsum;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询