FIND-MAX-CROSSING-SUBARRAY(A,low,mid,high) left_sum = -INFsum = 0for i = mid downto low sum = sum + A[i]if sum > left_sum left_sum = sum max_left = iright_sum = -INFsum = 0for j = mid+1 to high sum = sum+A[j]if sum > right_sum right_sum = sum max_right = jreturn(max_left,max_right ,left_sum+right_sum)
求解最大子数组算法会
调用自身两次并且
寻找跨越中点的最大子数组,时间复杂度为
FIND-MAXIMUM-SUBARRAY(A,low,high) if high == low //base casereturn(low,high,A[low])else mid = (low+high)/2 (left_low,left_high,left_sum) = FIND-MAXIMUM-SUBARRAY (A,low,mid) (right_low,right_high,right_sum) = FIND-MAXIMUM-SUBARRAY (A,mid+1,high) (cross_low,cross_high,cross_sum) = FIND-MAX-CROSSING-SUBARRAY (A,low,mid,high)if left_sum >= right_sum and left_sum >= cross_sumreturn (left_low,left_high,left_sum)elseif right_sum >= left_sum and right_sum >= cross_sumreturn (right_low,right_high ,right_sum)elsereturn(cross_low,cross_high ,cross_sum)