M1 Divide&Conquer - Maximum subarray sum
M1 Divide&Conquer - Maximum subarray sum
• To find maximum subarray sum (contiguous) of given 1-D array. Array may contain
negative and positive numbers which makes this a difficult problem. Brute force will take
O(N^2) time while a divide and conquer approach will take O(N log N) time.
• If all the array entries were positive, then the maximum-subarray problem would present no
challenge, since the entire array would give the greatest sum.
• Example : input array = [-3,2,3,4,-4,-1].
• here maximum subarray is [2,3,4]. hence maximum subarray sum is 9.
Left_Right_MaximumSubarray(A,l Midpoint_Crosssum(A,low,
ow,high) mid,high)
sum=0
if high==low // base case
return A[low] leftsum=-∞
else for i=mid downto low
mid=(low + high)/2 sum=sum+A[i]
leftsum=Left_Right_MaximumSubar if sum>leftsum
leftsum=sum
ray(A,low,mid)
rigthsum=Left_Right_MaximumSub sum=0
rightsum=-∞
array(A,mid+1,high)
midcrosssum=Midpoint_Crosssum( for i=mid+1 to high
sum=sum+A[i]
A,low,mid,high)
return if sum>rightsum
rightsum=sum
maximum(leftsum,rightsum,midcros
ssum) return leftsum+rightsum
endfunction endfunction