Last active
November 17, 2016 00:42
-
-
Save travisofthenorth/018dd777e908696bb1f2b9975764cb83 to your computer and use it in GitHub Desktop.
Determine if a contiguous set of positive integers in an array add up to n
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
class Array | |
def contains_sum?(n) | |
return false if n.nil? | |
low = 0 | |
high = 0 | |
sum = first | |
while sum != n && low < size | |
if sum < n || low == high | |
return false if high == size - 1 | |
high += 1 | |
sum += self[high] | |
elsif sum > n | |
sum -= self[low] | |
low += 1 | |
end | |
end | |
sum == n | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Testing: