1.题目要求
####题目 最大连续子数组和(最大子段和) ####背景 给定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。 ##2.程序设计
####主要算法 Max = max(Max, this_max = this_max + arr[i] > 0 ? this_max + arr[i] : 0),流程图如下。 ![](https://img2018.cnblogs.com/blog/1644656/201904/1644656-20190420154125960-944676939.png) ####代码地址 [我的代码](https://dev.tencent.com/u/dtid_0ddf9e1343024e5a/p/ruanjiangongchengdisancizuoye/git/blob/master/作业3) ####主要代码 ``` int dp(int arr[], int len) { int this_max = 0; int Max = 0; for (int i = 0; i < len; i++) { Max = max(Max, this_max = this_max + arr[i] > 0 ? this_max + arr[i] : 0); } return Max; ``` ##3.测试
####测试方法 条件覆盖,根据条件覆盖设计以下四组样例 ``` arr[]={1,2,3,4,5,6};//全为正数 arr[]={-1,-1,-1,-1,-1,-1};//全为负数 arr[]={0,0,0,0,0,0};//全为0 arr[]={-1,3,-4,5,-1,2};//正常情况 ``` ####测试代码 ``` namespace UnitTest1 { TEST_CLASS(UnitTest1) { public:
TEST_METHOD(TestMethod1)
{
int arr[] = { -2,11,-4,13,-5,-2 };
int len = 6;
int Max = dp(arr, len);
Assert::AreEqual(20, Max);
}
TEST_METHOD(TestMethod2)
{
int arr[] = { 1,2,3,4,5,6 };
int len = 6;
int Max = dp(arr, len);
Assert::AreEqual(21, Max);
}
TEST_METHOD(TestMethod3)
{
int arr[] = { -1,-1,-1,-1,-1,-1 };
int len = 6;
int Max = dp(arr, len);
Assert::AreEqual(0, Max);
}
TEST_METHOD(TestMethod4)
{
int arr[] = { 0,0,0,0,0,0 };
int len = 6;
int Max = dp(arr, len);
Assert::AreEqual(0, Max);
}
TEST_METHOD(TestMethod5)
{
int arr[] = { -1,3,-4,5,-1,2 };
int len = 6;
int Max = dp(arr, len);
Assert::AreEqual(6, Max);
}
};
}
####测试结果
![](https://img2018.cnblogs.com/blog/1644656/201904/1644656-20190420160044063-1455598496.png)