您的位置:首页 > 职场人生

面试题31:连续子数组的最大和

2013-09-30 14:45 309 查看
/*题目:输入一个整型数组,数组里有正数也有负数,数组中一个或连续的多个整数组成一个子数组。求所有子数组的和
的最大值。要求时间复杂度为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: