题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。
分析:
当加上一个正数时,和会增加;当加上一个负数时,和会减少。如果当前得到的和是个负数,那么这个和在接下来的累加中应该抛弃并重新清零,不然的话这个负数将会减少接下来的和。基于这样的思路,可以写出如下代码。
/*This is the template of *.cpp files */
#include<iostream>
using
namespace std;
int sub_max(int *in, int len){
int front
= 0;
int end = 0;
int max =
0;
int b = 0;
int i =
0;
int j = 0;
for(int k = 0; k <
len; ++k){
b += in[k];
if(b < 0){
i = k + 1;
j = k + 1;
b = 0;
}else{
j =
k;
if(b >
max){
front = i;
end = j;
max = b;
}
}
}
for(int l = front; l <=
end; ++l){
cout<<in[l]<<" ";
}
cout<<endl;
return
max;
}
int main(){
int test[8] =
{1,-2,3,10,-4,7,2,-5};
cout<<sub_max(test,
8);
return 0;
}
原文:http://www.cnblogs.com/candycloud/p/3580466.html