题目:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
C语言代码:
#include <stdio.h>
#include <time.h>
int a[11] = {-3,0,6,2,-1,-4,3,2,6,-90,6};
int main()
{
int maxd = 0;
int maxever = 0;
int count = 0;
int start = 0;
int thisstart =0;
int end = 0;
for(count = 0;count<11;count++)
{
maxd += a[count];
if(maxd < 0)
{
maxd = 0;
thisstart = count+1;
}
if(maxd > maxever)
{
start = thisstart;
maxever = maxd;
end = count;
}
}
printf("start = %d/t end = %d/t 最大子数组和 = %d/n",start,end,maxever);
getchar();
}