首页 > 代码库 > 【剑指offer】Q31:连续子数组的组大和

【剑指offer】Q31:连续子数组的组大和

简短的分析见:http://blog.csdn.net/shiquxinkong/article/details/17934747

def FindGreatestSumOfSubArray(array, index = None):
	curSum = 0
	maxSum = 0
	#return maxSum without the start and end index
	if index == None:
		for x in array:
			curSum = max(curSum, 0)
			curSum += x
			maxSum = max(maxSum, curSum)
		return maxSum
	#return maxSum and the start and end index	
	else:
		curS = -1
		curE = -1
		maxS = -1
		maxE = -1
		for i in range(len(array)):
			if curSum <= 0:
				curSum = array[i]
				curS = i
				curE = i
			else:
				curSum += array[i]
				curE = i
			if curSum > maxSum:
				maxS = curS
				maxE = curE
				maxSum = curSum
		return maxSum, maxS, maxE

这里通过index參数重载了两个版本号,一个只返回最大子段和,但有的时候我们可能还被要求返回取得最大子段和的起始区间。

上面的代码尽管看起来不像动态规划,可是思想确实是dp的思想。


【剑指offer】Q31:连续子数组的组大和