Skip to content

Instantly share code, notes, and snippets.

@natchiketa
Created June 23, 2015 19:39
Show Gist options
  • Save natchiketa/a1cf35720fc2df4dbc1d to your computer and use it in GitHub Desktop.
Save natchiketa/a1cf35720fc2df4dbc1d to your computer and use it in GitHub Desktop.
Tape equilibrium solution in JavaScript
function tapeEquilibrium(A) {
var p, idx;
var leftSum = 0, rightSum = 0;
var totalSum = 0;
var lastMin, currentMin;
var N = A.length;
if (N == 2) { return Math.abs(A[0] - A[1]); }
if (N == 1) { return Math.abs(A[0]); }
for (idx=0; idx < N; idx++) {
totalSum = totalSum + A[idx];
}
lastMin = Math.abs(totalSum - A[0] - A[0]);
for (p = 1; p <= N-1; p++) {
leftSum += A[p - 1];
rightSum = totalSum - leftSum;
currentMin = Math.abs(leftSum - rightSum);
lastMin = (currentMin < lastMin) ? currentMin : lastMin;
}
return lastMin;
}
@intelligent-rohit
Copy link

This is not giving correct result for var a = [-7, 1,5,2,-4, 3, 0 ];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment