Skip to content

Instantly share code, notes, and snippets.

@JazzyJosh
Created October 10, 2013 22:28
Show Gist options
  • Save JazzyJosh/481ef4a8143d780e80e9 to your computer and use it in GitHub Desktop.
Save JazzyJosh/481ef4a8143d780e80e9 to your computer and use it in GitHub Desktop.
This is my quickly thought out largest contiguous sum solution. I tested a couple of times with random 100 integer sets between -99 and 100. Seems to be accurate to me, please let me know if there is a fault. Wonderful little algorithm, and first time using Python too! Yes, I realize that's a tuple, not an array, but it was easier to type and th…
array = (98, 71, -71, 52, 45, -79, 38, -30, 21, 29 ,70, 14, -71, 64, 92, 46, -76, -92, -39, -83, 54, -23, 14, 34, -38, -61, 36, 69, -79, 91 ,-98, 38, 94, -33, -23, -17, -50, -92, -34, 18, 33, 96, 88, -77, -94, -24, -81, 7, -55, 20, 82, -60, 90, 19, 96, 19, -63, 94, 46, 39, -18, 59, 37, -76, -1, -32, -74, -40, 53, -66, 6, 31, 32, 43, 24, -20, 11, -54, 69, -90, -49, -97, -73, 83, -81, -8, 24, 87, 75, 94, 58, -46, -95, 23, 51, 41, -56, -1, -6, -71)
maxSum = array[0]
currentSum = array[0]
length = len(array)
begin = 0
end = 0
i = 1
while i < length:
currentSum += array[i]
if currentSum >= maxSum:
maxSum = currentSum
end = i
elif currentSum <= array[i]:
currentSum = array[i]
begin = i
i += 1
print maxSum
print "begin: %d end: %d" % (begin, end)
print array[begin:end+1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment