When I finished reading this problem,I thought I could solve it by scanning every single subarray in the array,and the time complexity is cubic.Every subarray could be the eventual one whose sum is the largest,so I did make a conclusion that the best time complexity is quadratic,and the only optimization is to reduce the times of addition,because I can keep track of the sum from array[i] to array[j] with a table(say table[arraylength][arraylength]).But even this DP-like skill can not reduce the time complexity to O(n).Then my friend told me there are room to optimize it,and the best time complexity is right O(n).
My first reaction is HOW.After think it over,I found I just miss something tricky.In the process of iteration,we could hit a position whose subarray sum is negative(say i,then array[0]+...+array[i]<0),then we can and should throw this part away.It is because negative sum would contribute negative factor to the following sum we are to look for.With this cool pattern,the time complexity can be optimized to O(n).The below is my code,please let me know if there is anything wrong.Thanks.
/*
author:zhouyou
date:2014/6/2
*/
#include <iostream>
#include <limits>
#include <algorithm> using namespace std; int GetMaxContiguousSubarraySum(int array[],const int arraylength)
{
if(!array || arraylength<=){
return numeric_limits<int>::min();//for error,return minimum of int
} int current_max = array[];
int Ret = array[];
for(int i=;i<arraylength;++i){
current_max = max(array[i],current_max+array[i]);
Ret = max(current_max,Ret);
}
return Ret;
} int main()
{
int array[] = {,,,-,,};
cout << GetMaxContiguousSubarraySum(array,) << endl;
return ;
}