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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下