Last active
October 19, 2016 00:16
-
-
Save MichaelWalker-git/7c3614c1d11037f32615baf767af9d44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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