求子数组的最大和
题目:
输入一个整形数组,数组里有正数也有负数。 //说明子数组之最大和一定大于0
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
ANSWER:
A traditional greedy approach. //让max为处于和最大的情况
题目:
输入一个整形数组,数组里有正数也有负数。 //说明子数组之最大和一定大于0
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
ANSWER:
A traditional greedy approach. //让max为处于和最大的情况
Keep current sum, slide from left to right, when sum < 0, reset sum to 0.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int MaxArray(int a[], int size, vector<int> &vec)
{
int sum = 0, max = 0;
max = - (1 << 31); //刚好在32位机器上的int型最小值 -2147183648 -2^31 ~ 2^31-1
int i=0;
int beg=0,end=0; //用来输出子序列
for(i=0;i<size;i++)
{
sum += a[i];
if(sum > max)
{
max = sum;
end = i;
}
else if(sum < 0)
{
sum = 0;
beg = i+1;
}
}
for(i=beg;i<=end;i++)
vec.push_back(a[i]);
return max;
}
int main()
{
vector<int> vec; //用来存放最大和的子序列
int a[]={1,-2,3,10,-4,7,2,-5};
int size = sizeof(a)/sizeof(a[0]);
int max = MaxArray(a,size,vec);
cout<<max<<endl;
for(vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++)
cout<<*iter<<endl;
return 0;
}