webdev: (Default)
[personal profile] webdev
Continuing the series on JavaScript Interview Questions, here's the next one: given an array of positive and negative integers, find the largest continuous sum.

This is pretty simple to do in JavaScript and uses the same algorithm that Arden describes in his original post:
function optimalSolution(arrIntegers) {
    var maxSum = 0,
        currentSum = 0,
        i = 0,
        arrIntegersLength = arrIntegers.length;
    
    if (arrIntegersLength === 0) {
        return;
    }
    
    for (i = 0; i < arrIntegersLength; i++) {
        currentSum = Math.max((currentSum+arrIntegers[i]), arrIntegers[i]);
        maxSum = Math.max(currentSum, maxSum);
    }
    return maxSum
}

Here I have optimized the loop but otherwise it's almost exactly the same as Arden's solution in Python.

Profile

webdev: (Default)
Jon Reid

October 2013

S M T W T F S
  12 345
6789101112
13141516171819
20212223242526
272829 3031  

Links