JavaScript 中具有最大和的子集
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 9:48:17
我们需要编写一个 JavaScript 函数,该函数接受一个整数数组。我们的函数需要找到具有最大和的非相邻元素的子集。
最后,该函数应计算并返回该子集的总和。
例如 −
如果输入数组是 −
const arr = [3, 5, 7, 8, 10];
那么输出应该是 20,因为非相邻的数字子集将是 3、7 和 10。
示例
其代码为 −
const arr = [3, 5, 7, 8, 10];
const maxSubsetSum = (arr = []) => {
let min = −Infinity
const helper = (arr, ind) => {
if ( ind < 0 ){
return min
};
let inc = helper(arr, ind−2);
let notInc = helper(arr, ind−1);
inc = inc == min ? arr[ind] : Math.max(arr[ind], arr[ind] + inc);
return Math.max( inc, notInc );
};
return helper(arr, arr.length − 1);
};
console.log(maxSubsetSum(arr));
输出
控制台中的输出将是 −
20
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

