一个整型数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。 例如输入的数组为1,-2,3,10,-4,7,2,-5,那么最大的子数组为3,10,-4,7,2,因此输出为该子数组的和18。
原先自己实现了一个很复杂的程序,思路虽然也是分段处理,之中用到了几个变量,处理起来感觉很难受。
昨晚在《编程珠玑》上看到了这道题,人家在O(n)的时间复杂度和O(1)的空间复杂度很干脆利落的解决了,解决的思路在于:最大连续子数组和要么出现在该元素,要么出现在加上下一个元素之后。
将书上的伪代码实现了一下,不得不说,一个问题之所以“复杂”,往往是思维还不够简单,很多问题从简单的方式去思考,不仅解决的很漂亮,而且解决的很舒服。
上代码(这段代码仅针对数组正负数均存在的情况,如果全为负数,则返回0):
#include <iostream> #include <string> using namespace std; int maxSum(int sz[], int len) { int maxSumHere = 0; int maxSumCur = 0; int i = 0; for(; i<len; i++) { if(maxSumHere + sz[i] > 0) maxSumHere = maxSumHere + sz[i]; else maxSumHere = 0; if(maxSumHere > maxSumCur) maxSumCur = maxSumHere; } return maxSumCur; } int main() { int sz[] = {1,-2,3,10,-4,7,2,-5}; cout<<maxSum(sz, sizeof(sz)/sizeof(int))<<endl; string str; std::cin>>str; return 0; }
#include <iostream> #include <string> #include <cmath> using namespace std; int maxSum(int sz[], int len) { int maxSumHere = 0; //统计截至到该元素为止最大的子数组和 int maxSumCur = 0; //统计截至到该元素为止前面最大的子数组和 int maxNegative = sz[0]; //统计最大的负数 int i = 0; for(; i<len; i++) { if(sz[i] < 0) //统计最大的负数 maxNegative = abs(sz[i])<abs(maxNegative)?sz[i]:maxNegative; if(maxSumHere + sz[i] > 0) //最大子数组和是截至到该元素,还是出现在下一个元素? maxSumHere = maxSumHere + sz[i]; else maxSumHere = 0; if(maxSumHere > maxSumCur) //统计到目前为止最大子数组和 maxSumCur = maxSumHere; } if(maxSumCur == 0) return maxNegative; else return maxSumCur; } int main() { int sz[] = {1,-2,3,10,-4,7,2,-5}; cout<<maxSum(sz, sizeof(sz)/sizeof(int))<<endl; int sz2[] = {-1, -2, -3, -4, -5}; cout<<maxSum(sz2, sizeof(sz2)/sizeof(int))<<endl; string str; std::cin>>str; return 0; }