This question comes from "data structure and algorithm", the book introduces four kinds of methods altogether, here put out two kinds.
1. Divide and conquer recursion, for the subject, although there are better algorithms, but it is useful to understand the divide and conquer algorithm with this problem
1#include <iostream>2 intMaxsublink (int*a,intRightintLeft );3 usingstd::cout;4 usingstd::cin;5 6 intMain ()7 {8 inta[8]={4,-3,5,-2,-1,2,6,-2};9 intMaxnum=maxsublink (A,0,7);Tencout<<Maxnum; One return 0; A } - intMaxsublink (int*a,intLeftintRight ) - { the intRightmax,leftmax; - intLeftbordermax,rightbordermax; - intLeftborder,rightborder; - + if(left==Right ) - { + if(a[left]>0) A returnA[left]; at Else - return 0; - } - intmid,i; -Mid= (Right+left)/2; -leftmax=Maxsublink (a,left,mid); inRightmax=maxsublink (a,mid+1, right); -leftborder=leftbordermax=0; to for(i=mid;i>=left;i--) + { -leftborder+=A[i]; the if(leftborder>Leftbordermax) *leftbordermax=Leftborder; $ }Panax Notoginsengrightborder=rightbordermax=0; - for(i=mid+1; i<=right;i++) the { +rightborder+=A[i]; A if(rightborder>Rightbordermax) therightbordermax=Rightborder; + } - intintermax=leftbordermax+Rightbordermax; $ if(intermax>=Rightmax) $ { - if(intermax>=Leftmax) - returnIntermax; the Else - returnLeftmax;Wuyi } the Else - { Wu if(rightmax>=Leftmax) - returnRightmax; About Else $ returnLeftmax; - } -}
2. Traverse the entire array, each of the traversed values is saved into Thissum, when thissum<0, Thissum 0; when Thissum>max, update max
This method of time complexity can reach O (n), the sense that this programming method is well worth learning, and in other algorithms are often used, very typical.
1#include <iostream>2 3 using namespacestd;4 intMaxsublink (int*a,intnum);5 intMain ()6 {7 inta[8]={4,-3,5,-2,-1,2,6,-2};8 intMaxnum=maxsublink (A,8);9cout<<Maxnum;Ten return 0; One } A intMaxsublink (int*a,intnum) - { - inti,thissum,maxsum; themaxsum=thissum=0; - for(i=0; i<num;i++) - { -thissum+=A[i]; + if(thissum>maxsum) -maxsum=thissum; + Else if(thissum<0) Athissum=0; at } - returnmaxsum; -}
"C + +" Maximum sub-columns