阅读更多
本文件实现数组最大子序列问题的四种复杂度的实现。
//立方复杂度
int maxsubsum1(int *array,size_t sz)
{
int maxsum = array[0];
for(size_t i = 0; i < sz; ++i)
for(size_t j = i; j < sz; ++j)
{
int thissum = 0;
for(size_t k = i; k <= j; ++k)
thissum += array[k];
if(thissum > maxsum)
maxsum = thissum;
}
return maxsum;
}
//平方复杂度
int maxsubsum2(int *array,size_t sz)
{
int maxsum = array[0];
for(size_t i = 0; i < sz; ++i)
{
int thissum = 0;
for(size_t j = i; j < sz; ++j)
{
thissum += array[j];
if(thissum > maxsum)
maxsum = thissum;
}
}
return maxsum;
}
//分治法(O(NlogN)复杂度)
int maxsubsum3(int *array,int left,int right)
{
if(left == right)
return array[left];
int mid = (right+left) / 2;
int rthissum=0,lthissum=0,
rmaxsum=0,lmaxsum=0;
int lmax = maxsubsum3(array,left,mid);
int rmax = maxsubsum3(array,mid+1,right);
for(int i = mid; i >= left; --i)
{
lthissum += array[i];
if(lthissum > lmaxsum)
lmaxsum = lthissum;
}
for(int i = mid+1; i <= right; ++i)
{
rthissum += array[i];
if(rthissum > rmaxsum)
rmaxsum = rthissum;
}
int max = rmaxsum + lmaxsum;
if(max >= rmax)
if(max >= lmax)
return max;
else
return lmax;
else if(rmax >= lmax)
return rmax;
else
return lmax;
}
//线性复杂度
int maxsubsum4(int *array,size_t sz)
{
int maxsum=array[0],thissum=0;
for(size_t i = 0; i < sz; ++i)
{
thissum += array[i];
if(thissum > maxsum)
maxsum = thissum;
else if(thissum < 0)
thissum = 0;
}
return maxsum;
}