JavaScript 中分区平均值的最大总和
问题
我们需要编写一个JavaScript函数,它接受一个数字数组arr作为第一个参数,以及一个数字num(num<=sizeofarr)作为第二个参数。
我们的函数应该将数组arr划分为最多num个相邻(非空)组,这样我们就不会留下任何元素。
从所有这些分区中,我们的函数应该选择所有组的平均值之和最大的那个分区。
最后我们应该返还这个最大的金额。
例如,如果函数的输入是
输入
const arr = [10, 2, 3, 4, 10]; const num = 3;
输出
const output = 23;
输出说明
因为如果我们像这样对数组进行分区-
[10], [2, 3, 4], [10]
平均值的总和将是-
10 + (9)/3 + 10 = 23
哪个是所有分区中最大的。
示例
以下是代码-
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输出结果 23