leetcode第53题,典型题,必考题,寻找最大和子序列,典型方法,分治法和动态规划。
分治法
def maxSub(nums,low,high):
if low >= high:
return nums[low]
mid = (low+high)/2
s1 = maxSub(nums,low,mid)
s2 = maxSub(nums,mid+1,high)
tempSum = 0
midRightMax = float('-inf')
midLeftMax = float('-inf')
for i in range(mid+1,high+1):
tempSum += nums[i]
if tempSum > midRightMax:
midRightMax = tempSum
tempSum = 0
for i in range(mid,low-1,-1):
tempSum += nums[i]
if tempSum > midLeftMax:
midLeftMax = tempSum
s3 = midLeftMax+midRightMax
return max(s1,s2,s3)
动态规划法,这个方法比较难理解,脱离状态转移方程,从这个题本身来看,动态规划的意义是这样的。首先,负数不能作为所求子序列的开头,很明显,如果选负数做开头,则从这个数下一个数开始的同样的子序列肯定比原子序列的和要大,由此继续推,和为负数的子序列不是所求子序列的前缀,因为有了第一条保证,这说明和为负数的子序列当中无论用哪个数作为开头,它其中的一段必然为负数,这样选用和为负数的子序列的下一个数作为开头的话,比原子序列要大,这就矛盾了。
def maxSub2(nums):
n = len(nums)
tempSum = 0
maxSum = 0
for i in range(n):
tempSum += nums[i]
if tempSum > maxSum:
maxSum = tempSum
elif tempSum < 0:
tempSum = 0
return maxSum