How do I optimise this javascript function for speed? -
i took codility tape equilibrium test here
as can see score didn't enough on how fast function executes. can give me pointers can optimise code , closer 100%?
here code...
function solution(a) { var minimumabsdiff = null; for(var currentindex =1;currentindex < a.length;currentindex ++){ var bottomhalf = gettotal(0,currentindex-1,a); var tophalf = gettotal(currentindex,a.length-1,a); var absdiff = math.abs(bottomhalf - tophalf); if(minimumabsdiff == null){ minimumabsdiff = absdiff; }else{ if(absdiff < minimumabsdiff) minimumabsdiff = absdiff; } } return minimumabsdiff; } function gettotal(start,end,arraytocheck){ var total = 0; for(var currentindex = start;currentindex <= end;currentindex++){ total = total + arraytocheck[currentindex]; } return total; }
you don't want optimise speed. want lower algorithmic complexity. current algorithm o(n²)
, while taks description explicitly stated that
- expected worst-case time complexity o(n);
- expected worst-case space complexity o(n), beyond input storage (not counting storage required input arguments).
so what's insight make possible? each total difference small distance others p
. if compare value |(a[0] + ... + a[p-1]) - (a[p] + ... + a[n-1])|
p
, p+1
, there constant amount of work difference done.
function solution(a) { var left = 0, right = a.reduce(function(a, b) { return + b; }, 0); var min = infinity; (var p = 0; p<a.length-1; p++) { left += a[p]; right -= a[p]; min = math.min(min, math.abs(left - right)); } return min; }
Comments
Post a Comment