典型分治思想,连续子数组必然位于以下三种情况之中:
1、完全位于A[low..mid]中,因此low <= i <= j <= mid.
2、完全位于A[mid..high]中,因此mid <= i <= j <= high.
3、跨越了中点,因此low <= i <= mid < j <= high.
求sum:
def max_child2(alist, low, high):
if low == high:
return alist[low]
mid = (low + high) // 2
m1 = max_child2(alist, low, mid)
m2 = max_child2(alist, mid+1, high)
now_left = alist[mid]
left = alist[mid]
for i in range(mid-1, low-1, -1):
now_left = now_left + alist[i]
if now_left > left:
left = now_left
now_right = alist[mid+1]
right = alist[mid+1]
for j in range(mid+2, high+1):
now_right = now_right + alist[j]
if now_right > right:
right = now_right
m3 = left + right
result = max(m1,m2,m3)
return result
求sum和index:
def MaxCrossSubArray(A,low,mid,high):
LeftMaxSum=A[mid]
leftSum=A[mid]
leftIndex=mid
for i in range(mid-1,low-1,-1):
leftSum=leftSum+A[i]
if leftSum>LeftMaxSum:
LeftMaxSum=leftSum
leftIndex=i
rightMaxSum=0
rightSum=0
rightIndex=mid
for i in range(mid+1,high+1):
rightSum+=A[i]
if rightSum>rightMaxSum:
rightMaxSum=rightSum
rightIndex=i
MaxSum=LeftMaxSum+rightMaxSum
return (MaxSum,leftIndex,rightIndex)
def MaxSubArray(A,low,high):
if low==high:
return (A[low],low,high)
mid=(low+high)//2
Left=MaxSubArray(A,low,mid)
Cross=MaxCrossSubArray(A,low,mid,high)
Right=MaxSubArray(A,mid+1,high)
List=[Left,Cross,Right]
result=sorted(List,key = lambda list : list[0],reverse=True)
return result[0]
a=[13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(MaxSubArray(a,0,len(a)-1))