We have an array of arrays that contains some numbers, we have to write a function that returns the takes in that array and returns the index of the subarray that has the maximum sum. If more than one subarray has the same maximum sum, we have to return the index of first such subarray.
Therefore, let’s write the code for this −
Example
const arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]; const findMaxSubArray = (arr) => { const add = (array) => array.reduce((acc, val) => acc+val); return arr.reduce((acc, val, ind) => { const sum = add(val); if(sum > acc.sum){ return { index: ind, sum } }; return acc; }, { index: -1, sum: -Infinity }).index; }; console.log(findMaxSubArray(arr));
Output
The output in the console will be −
3