Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const tapeEquilibrium = function(array) {
- let leftSum = array[0];
- let rightSum = array[array.length-1];
- if (array.length < 3) {
- return Math.abs(leftSum - rightSum);
- }
- let leftIndex = 1;
- let rightIndex = array.length-2;
- while (leftIndex <= rightIndex) {
- let leftElement = array[leftIndex];
- let rightElement = array[rightIndex];
- let newLeftSum = leftSum + leftElement;
- let newRightSum = rightSum + rightElement;
- let differenceAddingToLeft = Math.abs(newLeftSum - rightSum);
- let differenceAddingToRight = Math.abs(leftSum - newRightSum);
- if (differenceAddingToLeft <= differenceAddingToRight) {
- leftSum = newLeftSum;
- leftIndex++;
- } else {
- rightSum = newRightSum;
- rightIndex--;
- }
- }
- return Math.abs(leftSum - rightSum);
- }
- tapeEquilibrium([3,1,2,4,3]) === 1;
- tapeEquilibrium([3,-100,2,4,3]) === 94;
- tapeEquilibrium([3,-100]) === 103;
- tapeEquilibrium([-99,1000,-100]) === 999;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement