This is a test post to check if I can work on stackedit and
them just export the article to WordPress,
hmmm…
let me try
Written with StackEdit.
# a is the array, start, mid and end are the respective array indices
def maxsubarray3(a,start,mid,end):
# if want to find the actual subarray which gives us this maximum value for its sum
ansstart=mid
ansend=mid+1
# we need to find both sums of the left maxsubarray and the right maxsubarray.
# the sum of which will be the sum of the joint subarray (from i to j) the actual max subarray of a
# where i and j are such that,
# The subarray from i to mid_index is the maximum you can get
# from all subarrays where i which is before mid_index
# keeps track of all the the possible subarray sums
tempsum=0
# keeps track of the current top sum (for the left half)
# initially keep it as a very negative number
leftsum=-1
# lets take first half and find the maximum subarray,
# start from mid and by decrementing ( therefore the -1 )
# and go till the 1st element ( therefore till array indice start )
# ( Note that the range(a,b,c) function produces a list of a,a+c,a+2c,.. so on till b-1 )
# ( we need to write start-1 to get till start )
for i in range(mid,start-1,-1):
tempsum=tempsum+a[i]
if(tempsum>leftsum):
# the new top sum
leftsum=tempsum
ansstart=i
# just like how we got the leftsum, repeat for right sum.
tempsum=0
rightsum=-1
# we now check for all possible subarrays in the right half, ie
# mid+1 till end ( Note that the range(a,b,c) function
# produces a list of a,a+c,a+2c,.. so on till b-1 )
for j in range(mid+1,end+1):
tempsum=tempsum+a[j]
if(tempsum>rightsum):
# the new top sum
rightsum=tempsum
ansend=j
return (rightsum+leftsum)
# Actual function to solve the max subarray problem
def maxsubarray(a,start,end):
# Base case when recursion caused the array to finally become a single element
# the element itself is the only sum, therefore the maximum
if(start==end):
return a[start]
# find mid - an integer as its going to be used as a index
mid=int((start+end)/2)
# now we can find the maximum of the 3 cases
# we divide the array a into 2 parts (0 to mid) and (mid+1 to end), if the "maxsubarray" is a subarray of these 2 halfs we can find so by calling recursively
# else if the subarray we seek is that which crosses the middle element, then we call the maxsubarray3 function
return max(maxsubarray(a,start,mid),maxsubarray(a,mid+1,end),maxsubarray3(a,start,mid,end))