Created
February 22, 2021 02:53
-
-
Save phobon/126ff93a3c13e8717d2129ba4a4a8e09 to your computer and use it in GitHub Desktop.
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
const balancedSum = (arr) => { | |
// Find the left and right parts of the array, start from the middle cos it's as good a place as any | |
let i = Math.floor(arr.length / 2) | |
let left = arr.slice(0, i).reduce((a, b) => a + b, 0) | |
let right = arr.slice(i + 1).reduce((a, b) => a + b, 0) | |
// If they're equal, you beauty | |
if (left === right) { | |
return i | |
} | |
// We can compare them. We know the array is sorted... | |
// so we know that if left < right, we need to remove the first item from right and add to left | |
// and vice-versa. We can also assume there will always be a solution so.... | |
let iterations = 0 | |
while (left !== right) { | |
iterations += 1 | |
if (left < right) { | |
// Add to the left, remove from the right | |
left += arr[i] | |
right -= arr[i + 1] | |
// Increment the index | |
i += 1 | |
} else { | |
// Add to the right, remove from the left | |
right += arr[i] | |
left -= arr[i - 1] | |
// Decrement the index | |
i -= 1 | |
} | |
} | |
console.log(`${iterations} iteration(s)`) | |
return i | |
} | |
console.log(balancedSum([1, 2, 3, 4, 6])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment