Last active
October 14, 2015 16:15
-
-
Save akaila/552f88ae95593883db10 to your computer and use it in GitHub Desktop.
Given an array of positive integers and a target integer, find if there is a consecutive subarray that sums to the target. E.g, given {5,6,4,12}, findsum(10)=true, findsum(11)=false.
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
/* | |
Given an array of positive integers and a target integer, find if there is a consecutive subarray that sums to the target. | |
E.g, given {5,6,4,12}, findsum(10)=true, findsum(11)=false. | |
http://www.glassdoor.com/Interview/Given-an-array-of-positive-integers-and-a-target-integer-find-if-there-is-a-consecutive-subarray-that-sums-to-the-target-QTN_984284.htm | |
*/ | |
function findSubarraySum(numbers, sum) { | |
var sumSoFar = 0; | |
var start = 0; | |
var end = 0; | |
while (start < numbers.length) { | |
if (sumSoFar == sum) { | |
return true; | |
} else if (sumSoFar > sum) { | |
sumSoFar -= numbers[start]; | |
start++; | |
} else if (end < numbers.length) { | |
sumSoFar += numbers[end]; | |
end++; | |
} | |
} | |
return (sumSoFar == sum); | |
} | |
console.log(findSubarraySum([5,6,4,12], 11)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment