Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument, and a number, num, (num <= size of arr), as the second argument.
Our function should partition the array arr into at most num adjacent (non-empty) groups in such a way that we leave no element behind.
From all such partitions, our function should pick that partition where the sum of averages of all the groups is the greatest.
And lastly we should return this greatest sum.
For example, if the input to the function is
Input
const arr = [10, 2, 3, 4, 10]; const num = 3;
Output
const output = 23;
Output Explanation
Because if we partition the array like this −
[10], [2, 3, 4], [10]
The sum of averages will be −
10 + (9)/3 + 10 = 23
Which is the greatest among all partitions.
Example
Following is the code −
const arr = [10, 2, 3, 4, 10]; const num = 3; const greatestSum = (arr, num) => { const sum = (arr = []) => arr.reduce((acc, num) => acc + num, 0) let matrix = new Array(num + 1).fill(0).map(() => new Array(arr.length + 1).fill(0)) for (let index = arr.length; index >= 0; index--) { const current = new Array(num + 1).fill(0).map(() => new Array(arr.length + 1).fill(0)) for (let currentK = num; currentK >= 0; currentK--) { for (let count = arr.length - 1; count >= 0; count--) { if (index === arr.length && currentK === num) { current[currentK][count] = 0 } else if (index < arr.length && currentK < num) { current[currentK][count] = Math.max( matrix[currentK][count + 1],matrix[currentK + 1][0] + sum(arr.slice(index - count, index + 1)) / (count + 1) ) } else { current[currentK][count] = -Infinity } } } matrix = current } return matrix[0][0] } console.log(greatestSum(arr, num));
Output
23