for a brief analysis, see:http://blog.csdn.net/shiquxinkong/article/details/17934747
def findgreatestsumofsubarray (array, index = None): cursum = 0maxSum = 0#return maxsum without the start and end indexif in Dex = = None:for x in array:cursum = max (cursum, 0) cursum + = Xmaxsum = Max (maxsum, cursum) return Maxsum#return maxsum and T He start and end indexelse:curs = -1cure = -1maxs = -1maxe = -1for i in range (len (array)): if cursum <= 0:cursum = array [i]curs = Icure = Ielse:cursum + = Array[i]cure = IIf cursum > maxsum:maxs = cursmaxe = Curemaxsum = Cursumreturn MaxSum , Maxs, Maxe
There are two version numbers that are overloaded with index parameters, one that only returns the maximum number of sub-segments, but sometimes we may also be asked to return the starting range that gets the maximum sub-segment.
Although the above code does not look like dynamic programming, the idea is actually DP.
"The sword means offer" Q31: Group of contiguous sub-arrays Yamato