您的位置:首页 > 其它

(微软100题)3.求子数组的最大和

2014-02-14 17:22 162 查看
#include <iostream>
using namespace std;
/*3.求子数组的最大和
题目:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
ANSWER:
A traditional greedy approach.
Keep current sum, slide from left to right, when sum < 0, reset sum to 0.
*/
int maxSubarray(int a[], int size)
{
if (size<=0)
cout<<("error array size");
int sum = 0;
int max = - (1 << 31);
int cur = 0;
while (cur < size)
{
sum += a[cur++];
if (sum > max)
{
max = sum;
} else if (sum < 0)
{
sum = 0;
}
}
return max;
}

void main()
{
int test[8] = {1,-2,3,10,-4,7,2,-5};
cout<<maxSubarray(test,8)<<endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: