Created
June 23, 2015 19:39
-
-
Save natchiketa/a1cf35720fc2df4dbc1d to your computer and use it in GitHub Desktop.
Tape equilibrium solution in JavaScript
This file contains hidden or 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, 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not giving correct result for
var a = [-7, 1,5,2,-4, 3, 0 ];