/*题目:输入一个整型数组,数组里有正数也有负数,数组中一个或连续的多个整数组成一个子数组。求所有子数组的和
的最大值。要求时间复杂度为O(n)。*/
#include <iostream>
using namespace std;
bool g_InvalidInput = false;
int FindGreatestSumofSubarrary(int a[], int n)
{
//处理无效输入
if(a == NULL || n <= 0)
{
g_InvalidInput = true;
return 0;
}
int CurrentSum = 0;
int MaxSum = 0x80000000;//-2147483648
int start = 0;
int end = 0;
//遍历数组
for(int i = 0; i < n; ++i)
{
if(CurrentSum <= 0)
{
CurrentSum = a[i];
start = i;
}else
{
CurrentSum += a[i];
}
if(CurrentSum > MaxSum)
{
MaxSum = CurrentSum;
end = i;
}
}
if(start <= end)
{
for(int k = start; k <= end; ++k)
cout << a[k] << " ";
}else
{
cout << a[end];
}
cout << endl;
cout << MaxSum << endl;
return MaxSum;
}
//=================测试代码================
void Test(char *TestName, int a[], int n, int expectedresult, bool expectedflag)
{
if(TestName != NULL)
cout << TestName << " begins: " << endl;
int result = FindGreatestSumofSubarrary(a, n);
if(result == expectedresult && g_InvalidInput == expectedflag)
cout << "Passed!" << endl;
else
cout << "Failed!" << endl;
}
//===============测试用例=================
void Test1()
{
int data[] = {1, -2, 3, 10, -4, 7, 2, -5};
Test("Test1", data, sizeof(data) / sizeof(int), 18, false);
}
//全是负数
void Test2()
{
int data[] = {-2, -8, -1, -5, -9};
Test("Test2", data, sizeof(data) / sizeof(int), -1, false);
}
//全是正数
void Test3()
{
int data[] = {2, 8, 1, 5, 9};
Test("Test3", data, sizeof(data) / sizeof(int), 25, false);
}
//无效输入
void Test4()
{
Test("Test4", NULL, 0, 0, true);
}
int main()
{
Test1();
Test2();
Test3();
Test4();
return 0;
}
面试题31:连续子数组的最大和
最新推荐文章于 2021-09-13 15:59:49 发布