Read, think, write code!
/*************************************** * [email protected] * Blog:http://blog.csdn.net/hustyangju * Title: Divide and conquer the maximal continuous sub-sequence of the array and * ideas: Decomposition into sub-problem + combined answer * time complexity: O (n LGN) * Spatial complexity: O (1) ***************************************/#include < Iostream>using namespace Std;template<class type>class max_subarray{public:max_subarray (Type *p): _p (P) {} ~ Max_subarray () {} type Max_aside_subarray (int s,int e);p rotected:type max_cross_subarray (int s,int m,int e); Type _max (type A,type b,type c);p rivate:type *_p;}; Template<class type>type Max_subarray<type>::_max (Type A, type B, type C) {if (a>=b) && (a>=c) ) return A; else if ((b>=a) && (b>=c)) return B; else return C;} Template<class type>type Max_subarray<type>::max_cross_subarray (int s, int m, int e) {type left_sum=* (_p+m) ; Type right_sum=* (_p+m+1); for (int i=m;i>=s;i--) {type sum=0; sum+=* (_p+i); if (sum>left_sum) Left_sum=sum; }//for for (int i=m+1;i<=e;i++) {type sum=0; sum+=* (_p+i); if (sum>right_sum) right_sum=sum; }//for return (left_sum+right_sum);} Template<class type>type Max_subarray<type>::max_aside_subarray (int s, int e) {int m=0; Type left_sum,right_sum,cross_sum; if (s==e) return (* (_p+s)); Else M=int ((s+e)/2); Left_sum=max_aside_subarray (S,M); Cross_sum=max_cross_subarray (s,m,e); Right_sum=max_aside_subarray (m+1,e); Return _max (left_sum,cross_sum,right_sum);} int main () {int array1[10]={1,-2,-3,4,5,6,-7,-8,9,10}; Float array2[10]={1.0,-2.0,-3.0,4.0,5.2,6.0,-7.0,-8.0,9.0,-10.0}; Max_subarray<int> mysubarray1 (array1); Max_subarray<float>mysubarray2 (array2); cout<< "Max sum of sub array is:"; Cout<<mysubarray1.max_aside_subarray (0,9) <<endl; cout<< "Max sum of SubArray is: "; Cout<<mysubarray2.max_aside_subarray (0,9) <<endl;}
GitHub one-day algorithm: Divide-and-conquer method to find the maximal continuous sub-sequence of arrays and