Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

>Before going on, consider how you’d solve this yourself.

    var sum = 0;
    for(v : vals) {sum += 2*v;}
    sum -= (vals.first + vals.last);
simpler and much faster than any of the mentioned methods in the article.

(Proof: when you sum the neighbours of all the elements then you add each element twice except the first and the last one.)

Even simpler and even faster:

    var s = sum(vals) * 2 - vals.first - vals.last;


Even though the wording is a bit ambiguous, the problem is to output an array of neighbour-sums, not a single sum-of-neighbour-sums.


oh, ok, thanks.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: