给定一个数组,求出和最大的连续子数组。返回子数组的开始位,结束位,和。
思路:分治策略,将数组一分为二,最大子数组可能在左半,或右半,或横跨中间。不断分割,直到子问题可解,求出子数组,再逐步合并。
def Max_subarray(a,low,high): #初始输入的low和high应为0,len(a)-1
if high == low:
return [low, high, a[low]]
else:
mid = int((high+low)/2)
L = Max_subarray(a,low,mid)
R = Max_subarray(a,mid+1,high)
M = Max_cross_subarray(a,low,mid,high)
if L[2]>=R[2] and L[2]>=M[2]:
return L
if R[2]>=L[2] and R[2]>=M[2]:
return R
else:
return M
def Max_cross_subarray(a,low,mid,high):
max_left = mid
max_right = mid
left_sum = -float("inf")
right_sum = -float("inf")
sum = 0
i = mid
while i>= low:
sum = sum + a[i]
if sum >= left_sum:
left_sum = sum
max_left = i
i=i-1
sum = 0
j = mid+1
while j<= high:
sum = sum + a[j]
if sum >= right_sum:
right_sum = sum
max_right = j
j=j+1
return [max_left, max_right, left_sum+right_sum]