找到低于/等于给定限制的最高和

时间:2018-03-05 11:13:29

标签: javascript

我有以下功能:



var object = [12,23,14,35,24];
//debugger;
function f(objects, sum){
  var curSum = objects[0];
  var maxSum = 0;
  var start = 0;
  for (var i = 1; i < objects.length; i++) {
    while(curSum > sum && start < i){
      curSum -= objects[start];
      start++
    }
    maxSum = Math.max(maxSum, curSum);
    curSum += objects[i];
    if(curSum <= sum){
      maxSum = Math.max(curSum, maxSum);
    }
  }
  return maxSum;
}

console.log(f(object,50));
&#13;
&#13;
&#13;

由于元素12,14,24

,我希望最高可能总和为50

然而,我只能设法到达49.我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

您可以通过迭代数组并检查临时数组是否具有正确的总和并检查结果是否为eiter replaceinf较小的总和或推送到相同的总和部分来采取递归方法。

&#13;
&#13;
function combine(array, sum) {
    function fork(i, p) {
        var s = p.reduce((a, b) => a + b, 0),
            l = (result[0] || []).reduce((a, b) => a + b, 0);

        if (i === array.length) {
            if (s <= sum) {
                if (l < s) {
                    result = [p];
                }
                if (l === s) {
                    result.push(p);
                }
            }
            return;
        }
        fork(i + 1, p.concat(array[i]));
        fork(i + 1, p);
    }
    var result = [];
    fork(0, []);
    return result;
}

console.log(combine([12, 23, 14, 35, 24], 50));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Here你可以找到一个小提琴 这完全有效。
我使用我找到here的算法来查找数组中的所有组合:

function k_combinations(set, k) {
    var i, j, combs, head, tailcombs;
    if (k > set.length || k <= 0) {
        return [];
    }
    if (k == set.length) {
        return [set];
    }
    if (k == 1) {
        combs = [];
        for (i = 0; i < set.length; i++) {
            combs.push([set[i]]);
        }
        return combs;
    }
    combs = [];
    for (i = 0; i < set.length - k + 1; i++) {
        head = set.slice(i, i + 1);
        tailcombs = k_combinations(set.slice(i + 1), k - 1);
        for (j = 0; j < tailcombs.length; j++) {
            combs.push(head.concat(tailcombs[j]));
        }
    }
    return combs;
}

function combinations(set) {
    var k, i, combs, k_combs;
    combs = [];
    for (k = 1; k <= set.length; k++) {
        k_combs = k_combinations(set, k);
        for (i = 0; i < k_combs.length; i++) {
            combs.push(k_combs[i]);
        }
    }
    return combs;
}

然后,我创建了这个函数:

function findHighestSum(numbers, limit) {
    let summations = [];
  combinations(numbers).forEach(function(combination) {
    summations.push(combination.reduce(function(summation, n) {
        summation += n;
        return summation;
    }));
  });
  return summations.reduce(function(accumulator, x) {
    if (x > accumulator && x <= limit)
        accumulator = x;
    return accumulator;
  }, 0);
}

所以,您可以按如下方式使用它:

let sum = findHighestSum([12,23,14,35,24], 50);
alert(sum);