Skip to content

Instantly share code, notes, and snippets.

@alabid
Created September 16, 2012 22:15
Show Gist options
  • Save alabid/3734606 to your computer and use it in GitHub Desktop.
Save alabid/3734606 to your computer and use it in GitHub Desktop.
solution to max sub array problem in python
def maxSubArray(ls):
if len(ls) == 0:
raise Exception("Array empty") # should be non-empty
runSum = maxSum = ls[0]
i = 0
start = finish = 0
for j in range(1, len(ls)):
if ls[j] > (runSum + ls[j]):
runSum = ls[j]
i = j
else:
runSum += ls[j]
if runSum > maxSum:
maxSum = runSum
start = i
finish = j
print "maxSum =>", maxSum
print "start =>", start, "; finish =>", finish
maxSubArray([-2, 11, -4, 13, -5, 2])
maxSubArray([-15, 29, -36, 3, -22, 11, 19, -5])
@praton1729
Copy link

An easier approach has been mentioned on the Wikipedia page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment