求最大子序列和

#include<stdio.h>
#include<stdlib.h>
#include"random_n.h"

#define MAX_NUM 100
/*
*Function:the most powerful method to solve the problem
*
*Huge:T = O(N)
*
*Author:Qinzhiguo
*
*Date:2012-1-30
*/

int MaxSubSum_HighSpeed(int a[],int N)
{
int ThisSum,MaxSum,i,j;

ThisSum=MaxSum=0;
for(i=0;i<N;i++)
{

ThisSum += a[i];
if(ThisSum > MaxSum)
{
MaxSum=ThisSum;
}
else if(ThisSum <0)
{
ThisSum=0;
}

}

return MaxSum;
}

/*
*Function: Max3 is a method to get the biggest one of 3 input numbers
*
*Author:Qinzhiguo
*
*Date:2012-2-3
*
*/
int Max3(int a,int b,int c)
{
if(a>=b && a>=c)
{
return a;
}
else if(b>=a && b>=c)
{
return b;
}
else if(c>=a && c>=b)
{
return c;
}
else
{
return -1;
}
}

/*
*Function:a recursive method to get the sub maxmimu sum of the sequence
*
*Author:Qinzhiguo
*
*Date:2012-2-3
*/

int MaxSubQuenceSum(int a[],int left,int right)
{
int MaxLeftSum,MaxRightSum;
int MaxLeftBorderSum,MaxRightBorderSum;
int LeftBorderSum,RightBorderSum;
int center,i;

if(left == right)
{
if(a[left] >0)
{
return a[left];
}
else
{
return 0;
}

}

center = (left + right) / 2;

MaxLeftSum=MaxSubQuenceSum(a,left,center);
MaxRightSum=MaxSubQuenceSum(a,center+1,right);

MaxLeftBorderSum=0;
LeftBorderSum=0;
for(i=center;i>=left;i--)
{
LeftBorderSum += a[i];
if(LeftBorderSum > MaxLeftBorderSum)
{
MaxLeftBorderSum=LeftBorderSum;
}
}

MaxRightBorderSum=0;
RightBorderSum=0;
for(i=center+1;i<=right;i++)
{
RightBorderSum +=a[i];
if(RightBorderSum > MaxRightBorderSum)
{
MaxRightBorderSum=RightBorderSum;
}
}

return Max3(MaxLeftSum,MaxRightSum,MaxLeftBorderSum+MaxRightBorderSum);

}

/*
*Function:get the maxsubsum by giving the argments input.
*
*Author:Qinzhiguo
*
*Date:2012-2-3
*/
int MaxSubSum(int a[],int n)
{
return MaxSubQuenceSum(a,0,n-1);
}

/*
*Function:Main indoor of the whole project
*
*Author:Qinzhiguo
*
*Date:2012-1-31
*/
int main()
{
int a[MAX_NUM];
int i=0,MaxSum=0;
while(i<MAX_NUM)
{
a[i]=0;
i++;
}
random_n(a,MAX_NUM);
MaxSum = MaxSubSum(a,MAX_NUM);

i=0;
while(i<MAX_NUM)
{
printf("%d ",a[i]);
i++;
}
printf("\nThe List MaxSubQueneSum is %d\n",MaxSum);

if(i==0)
{
printf("\nNothing is done!\n");
}
else
{
printf("\n------------Program Finshed------------\n");
}
return 0;

}

头文件包含的random.h是我自己写的一个产生随机数的函数,大家可以自己实现,或者参考我之前博客中给出的生成随机数的方法。

这样在测试的时候具有比较大的优势,减去了大数据量的输入负担。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值