求最大连续子数组和

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>
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
	int number[50];
	int n,i,j,k;
	int sum = 0;
	int max = 0;
	cin >> n;
	for (i = 0; i < n; i++)
	{
		cin >> number[i];
	}
	for (int i = 0; i <n; i++)
	{
		for (int j = i; j < n; j++)
		{
			int sum = 0;
			
			for (int k = i; k <= j; k++)
			{
				sum+= number[k];
			}
			if (sum > max)
			{
				max = sum;
			}
		}
	}
	cout<<max;
	return 0;
}

程序代码已上传至coding.net最大连续子数组和

3.流程图

4.编写单元测试

我选用判定条件覆盖,使用五组测试用例


num[] = { 0 };
num[4] = { -2,-2,-3,-4 };
num[4] = { 4,2,6,5,};
num[4] = { 5,-2,3,4 };
num[4] = { 3,-8,6,4 };


测试代码如下:


            TEST_METHOD(TestMethod1)
	{
		int max, num[] = { 0 };
		max = test(num, 0);
		Assert::AreEqual(max, 0);
	}
	TEST_METHOD(TestMethod2)
	{
		int max, num[4] = { -2,-2,-3,-4 };
		max = test(num, 4);
		Assert::AreEqual(max, 0);
	}
	TEST_METHOD(TestMethod3)
	{
		int max, num[4] = { 4,2,6,5,};
		max = test(num, 4);
		Assert::AreEqual(max, 17);
	}
	TEST_METHOD(TestMethod4)
	{
		int max, num[4] = { 5,-2,3,4 };
		max = test(num, 4);
		Assert::AreEqual(max, 10);
	}
	TEST_METHOD(TestMethod5)
	{
		int max, num[4] = { 3,-8,6,4 };
		max = test(num, 4);
		Assert::AreEqual(max, 10);
            }

测试结果如下:

测试完毕!