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.
From:
Anonymous (will be screened)
OpenID (will be screened if not validated)
Identity URL: 
User
Account name:
Password:
If you don't have an account you can create one now.
Subject:
HTML doesn't work in the subject.

Message:

If you are unable to use this captcha for any reason, please contact us by email at support@dreamwidth.org


 
Notice: This account is set to log the IP addresses of everyone who comments.
Links will be displayed as unclickable URLs to help prevent spam.

Profile

webdev: (Default)
Jon Reid

October 2013

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

Links