Skip to content

Instantly share code, notes, and snippets.

@MichaelWalker-git
Last active October 19, 2016 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelWalker-git/7c3614c1d11037f32615baf767af9d44 to your computer and use it in GitHub Desktop.
Save MichaelWalker-git/7c3614c1d11037f32615baf767af9d44 to your computer and use it in GitHub Desktop.
function tapeEquilibrium(A) {
var p, i;
var leftSum = 0, rightSum = 0;
var totalSum = 0;
var lastMin, currentMin;
var leng = A.length;
if (leng == 2) { return Math.abs(A[0] - A[1]); }
if (leng == 1) { return Math.abs(A[0]); }
//edge cases where the length is 1 or 2
//iterate once to get the total sum of the array
for (i=0; i < leng; i++) {
totalSum = totalSum + A[i];
}
//sets the minimum value to the totalSum minus the first element twice
//twice because the total includes the value (first), then we subtract that new total (second)
lastMin = Math.abs(totalSum - A[0] - A[0]);
//excludes the first and last element of the array
//iterates
for (p = 1; p <= leng-1; p++) {
leftSum += A[p - 1];
//left sum is initally zero, but now is the sum of all the values to the left of the pointer
rightSum = totalSum - leftSum;
//using the left sum to determine the right sum
currentMin = Math.abs(leftSum - rightSum);
//determines the currentMin
lastMin = (currentMin < lastMin) ? currentMin : lastMin;
//lastMin is a global variable that is redefined
}
return lastMin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment