最大连续子数代码;
include <stdio.h>
int maxSubarraySum(int arr[], int n) {
int max_sum = INT_MIN, cur_sum = 0;
for (int i = 0; i < n; i++) {
cur_sum = std::max(arr[i], cur_sum + arr[i]);
max_sum = std::max(max_sum, cur_sum);
}
return max_sum;
}
int main() {
int arr[] = {-2, 11, -4, 13, -5, -2};
int n = sizeof(arr) / sizeof(arr[0]);
int max_sum = maxSubarraySum(arr, n);
printf("最大子段和为: %d\n", max_sum);
return 0;
}
测试代码:
include "stdafx.h"
include "CppUnitTest.h"
include "..\Max\标头.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
int arr[6] = { -2,11,-4,13,-5,-2 }, max;
max = Max(arr, 6);
Assert::AreEqual(max, 20);
}
TEST_METHOD(TestMethod2)
{
int arr[5] = { -1,2,3,-6,7 }, max;
max = Max(arr, 5);
Assert::AreEqual(max, 7);
}
TEST_METHOD(TestMethod3)
{
int arr[6] = { -2,-11,-4,-13,-5,-2 }, max;
max = Max(arr, 6);
Assert::AreEqual(max, 0);
}
TEST_METHOD(TestMethod4)
{
int arr[6] = { 1,2,3,4,5,6 }, max;
max = Max(arr, 6);
Assert::AreEqual(max, 21);
}
};
}
标签:arr,int,max,sum,软件工程,Max,TEST From: https://www.cnblogs.com/xiaotangao/p/18127423