一.题目要求
最大连续子数组和(最大子段和):
问题: 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
二.程序设计及代码
GITHUB代码地址<https://github.com/secondear/xxj>
1.思路分析
我们定义两个变量,sum(保存连续累加的和),max(连续子数组的最大值),都赋值为数组的第一个元素。然后从第二个元素开始依次遍历整个数组,从array[1]开始逐个进行相加,与最大值比较,并不停地更替最大值。
2.程序流程图
3.编写代码
int MaxsumUlt(int* arr, int subs)
{
if (arr == NULL)
return 0;
int Sum = arr[0];
int MAX = 0;
for (int i = 1; i < subs; i++)
{
if (Sum <= 0)
{
Sum = arr[i];
}
else
{
Sum += arr[i];
}
if (Sum >= MAX)
MAX = Sum;
}
return MAX;
}
三.调试程序
1.采用判定/条件覆盖测试程序设计
arr=NULL | Sum<=0 | Sum>=MAX |
---|---|---|
arr!=NULL | Sum>0 | Sum<MAX |
2.测试代码
TEST_METHOD(TestMethod1)
{
int* array = {};
int subs = sizeof(array) / sizeof(array[0]);
int MAX = MaxsumUlt(array, subs);
Assert::AreEqual(MAX, 0);
}
TEST_METHOD(TestMethod2)
{
int array[] = { -2,11,-4,13,-5,-2 };
int subs = sizeof(array) / sizeof(array[0]);
int MAX = MaxsumUlt(array, subs);
Assert::AreEqual(MAX, 20);
}
TEST_METHOD(TestMethod3)
{
int array[] = { -2,-11,-4,-13,-5,-2 };
int subs = sizeof(array) / sizeof(array[0]);
int MAX = MaxsumUlt(array, subs);
Assert::AreEqual(MAX, 0);
}
TEST_METHOD(TestMethod4)
{
int array[] = { 1,4,7 };
int subs = sizeof(array) / sizeof(array[0]);
int MAX = MaxsumUlt(array, subs);
Assert::AreEqual(MAX, 12);
}
3.测试样例
array{};
array{-2,11,-4,13,-5,-2};
array{-2,11,-4,-13,-5,-2};
array{1,4,7};