Created
May 3, 2012 16:38
-
-
Save drodriguez/2587067 to your computer and use it in GitHub Desktop.
Find partial consecutive sum
This file contains 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 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