Skip to content

Instantly share code, notes, and snippets.

@anttip
Last active December 25, 2015 10:29
Show Gist options
  • Save anttip/6961879 to your computer and use it in GitHub Desktop.
Save anttip/6961879 to your computer and use it in GitHub Desktop.
Coding for Interviews puzzle 10th October 2013. Looked like fun, so here's a quick try at it with javascript. The problem: Find the maximum sum possible from picking a contiguous subsequence of an array. [-1, 5, 6, -2, 20, -50, 4] What is the largest sum of contiguous elements available in this list? In the example above, the maximum sum would b…
function maxContiguousSum(f){
var maxSoFar=0 , maxNow=0, i;
for(i=0; i<f.length; i++){
maxNow = Math.max(0, maxNow+f[i]);
maxSoFar = Math.max(maxSoFar, maxNow);
}
return maxSoFar;
}
function test(expected, actual, msg){
if(expected!==actual){
throw new Error(msg);
}
}
test(29, maxContiguousSum([-1, 5, 6, -2, 20, -50, 4]));
test(6, maxContiguousSum([-2,1,-3,4,-1,2,1,-5,4]));
test(0, maxContiguousSum([]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment