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 代码实现
#include <stdio.h>
using namespace std;
int p(int x, int num[])
{
int sum[100];
sum[0] = 0;
for (int i = 1; i <= x; i++) {
sum[i] = num[i] + sum[i - 1];
}
int ans = num[1];
for (int i = 1; i <= x; i++) {
for (int j = i; j <= x; j++) {
int s = sum[j] - sum[i - 1];
if (s > ans) ans = s;
}
}
printf("%d\n", ans);
return ans;
}
int main()
{
int x, num[100];
scanf_s("%d", &x);
for (int i = 1; i <= x; i++)
scanf_s("%d", &num[i]);
p(x, num);
return 0;
}
代码地址:
3.单元测试选择方式
-
选择判定覆盖
-
路程图
-
测试数据
{-2,11,-4,13,-5,-2}
->{20}
测试代码
#include "CppUnitTest.h"
#include "E:\oooo\vvvv\vvvv\标头.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
int num[5] = { 1,2,3,4,-5 }, n = 5, MAX;
MAX = p(n, num);
Assert::AreEqual(MAX, 10);
}
TEST_METHOD(TestMethod2)
{
int num[5] = { 4,5,6,-10,-12 }, n = 5, MAX;
MAX = p(n, num);
Assert::AreEqual(MAX, 15);
}
TEST_METHOD(TestMethod3)
{
int num[5] = { -7,6,6,8,-10}, n = 5, MAX;
MAX = p(n, num);
Assert::AreEqual(MAX, 20);
}
};
}