Skip to content

Instantly share code, notes, and snippets.

@ehsania
Created May 30, 2013 17:16
Show Gist options
  • Save ehsania/5679547 to your computer and use it in GitHub Desktop.
Save ehsania/5679547 to your computer and use it in GitHub Desktop.
Simple implementation of maximum subarray (divide-and-conquer) in python
def findMaxCrossingSubArray(lst, low, high, mid):
l, h = 0, 0
i = mid
s = 0
leftsum = lst[i] - 1
while i >= low:
s = s + lst[i]
if s > leftsum:
leftsum = s
l = i
i = i - 1
j = mid + 1
s = 0
rightsum = lst[j] - 1
while j <= high:
s = s + lst[j]
if s > rightsum:
rightsum = s
h = j
j = j + 1
return (l, h, leftsum + rightsum)
def findMaxSubArray(lst, low, high):
if low == high:
return (low, high, lst[low])
mid = (low + high) / 2
llow, lhigh, leftSum = findMaxSubArray(lst, low, mid)
rlow, rhigh, rightSum = findMaxSubArray(lst, mid + 1, high)
clow,chigh, crossingSum = findMaxCrossingSubArray(lst, low, high, mid)
if leftSum > rightSum:
if leftSum > crossingSum:
return (llow, lhigh, leftSum)
else:
return (clow, chigh, crossingSum)
else:
if rightSum > crossingSum:
return (rlow, rhigh, rightSum)
else:
return (clow, chigh, crossingSum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment