Created
September 19, 2020 13:34
-
-
Save hassan-maavan/8539243bf11e8bdbd033a35f868986d6 to your computer and use it in GitHub Desktop.
Given an array nof integers, divide the array into two parts so that the sum of integers in one part is the same as the sum in other part.
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
// input [1,2,4,2,7,2] | |
//output [1,2,4,2] == 9 | |
[7,2] == 9 | |
const sum = (array) => array.reduce((total, val) => total + val); | |
const arr = [1,2,4,2,7,2]; | |
const arraySum = sum(arr) / 2; | |
let arr1 = [], arr2 = []; | |
for(i =0; i < arr.length; i++) { | |
if(sum([...arr1, arr[i]]) <= arraySum) | |
arr1.push(arr[i]) | |
else | |
arr2.push(arr[i]) | |
} | |
console.log(arr1, arr2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment