Skip to content

Instantly share code, notes, and snippets.

@drodriguez
Created May 3, 2012 16:38
Show Gist options
  • Save drodriguez/2587067 to your computer and use it in GitHub Desktop.
Save drodriguez/2587067 to your computer and use it in GitHub Desktop.
Find partial consecutive sum
def find_partial_sum(array, goal)
istart, iend, sum = 0, 0, 0
while iend < array.length
while iend < array.length && sum < goal
sum += array[iend]
iend += 1
end
while istart < iend && sum > goal
sum -= array[istart]
istart += 1
end
if sum == goal
return array[istart...iend]
end
end
return nil
end
puts find_partial_sum([2, 1, 3, 2, 1], 5).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment