Created
September 16, 2012 22:15
-
-
Save alabid/3734606 to your computer and use it in GitHub Desktop.
solution to max sub array problem in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It does not work as expected...
In the first case it should return 13 instead of 11