书p38页。主要的亮点是通过归并来大大降低了计算复杂度,并和投资股票的实例相结合
python代码:
def FindMaximumCrossinngSubarray(A,low,mid,high):
max_left = 0
max_right=0
left_sum = -float('inf')
sum = 0
for i in range(mid,low-1,-1):
sum = sum+A[i]
if sum>left_sum:
left_sum=sum
max_left= i
right_sum = -float('inf')
sum = 0
for i in range(mid+1,high-1):
sum = sum+A[i]
if sum>left_sum:
right_sum=sum
max_right= i
return max_left,max_right,(left_sum+right_sum)
def FindMaximumSubarray(A,low,high):
if low==high:
return low,high,A[low]
else:
mid = (low+high)//2
left_low,left_high,left_sum = FindMaximumSubarray(A,low,mid)
right_low,right_high,righ_sum = FindMaximumSubarray(A,mid+1,high)
cross_low,cross_high,cross_sum = FindMaximumCrossinngSubarray(A,low,mid,high)
if left_sum>=max(cross_sum,righ_sum):
return left_low,left_high,left_sum
elif righ_sum>=max(cross_sum,left_sum):
return right_low,right_high,righ_sum
else:
return cross_low,cross_high,cross_sum
A=[13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(FindMaximumSubarray(A,0,len(A)-1))