我的循环运行了两次,但没有为此提供正确的答案

时间:2019-12-10 16:35:53

标签: javascript algorithm list data-structures

**最大和子数组的问题在于找到最大和

  数组或整数列表中的连续子序列的

:   maxSequence([-2,1,-3,4,-1,2,1,-5,4])//应该为6:[4,-1,   2,1]最简单的情况是列表仅由正数组成   最大和是整个数组的和。如果列出了   只能是负数,请返回0。

     

空列表被认为具有零最大和。请注意,

空列表或数组也是有效的子列表/子数组。**

var maxSequence = function(arr) {
    // ...
    let max = 0;
    const sorted = arr.sort((a, b) => {
        return a - b;
    });
    if (arr.length == 0) {
        return 0;
    } else if (sorted[sorted.length - 1] >= 0 && sorted[0] >= 0) {
        let max = 0;
        for (let i = 0; i < sorted.length; i++) {
            max += sorted[i];
        }
        return max;
    } else if (sorted[0] < 0 && sorted[sorted.length - 1] < 0) {
        console.log(0);
    } else {
        let halfLength = Math.floor(arr.length / 2);
        let pivot = 0;
        let sequence = 0;
        let next = 1;
        while (pivot <= arr.length - 1) {
            if (arr[next] <= halfLength) {
                sequence += arr[next];
                next += 1;
            } else {
                sequence = 0;
                halfLength += 1;
                pivot += 1;
                next = pivot + 1;
            }

            if (pivot == arr.length - 2) {
                sequence += arr[next];
                next += 1;
                break;
            }

            if (sequence >= max) {
                max = sequence;
            }
        }
        console.log("the answer", max);
    }
};

maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]); //, 6)
  

**代码返回12而不是我现在已经尝试一个小时的任何解决方案6 **

1 个答案:

答案 0 :(得分:2)

您可以对所有组合进行测试,然后查看哪一种组合得分最高。

function maxSequence(data) {
  let result = {
    value: null,
    seq: null
  }

  let check = {
    pos: true,
    neg: true
  }

  data.forEach(e => {
    if (e > 0) check.neg = false;
    if (e < 0) check.pos = false;
  })

  if (check.pos) {
    return sum(data)
  } else if (check.neg) {
    return 0;
  }

  function sum(seq) {
    return seq.reduce((r, e) => r + e, 0)
  }

  for (let i = 0; i < data.length; i++) {
    for (let j = i; j < data.length; j++) {
      const seq = data.slice(i, j + 1);
      const seqSum = sum(seq);

      if (result.value === null || seqSum > result.value) {
        result.value = seqSum;
        result.seq = seq;
      }
    }
  }

  return result;
}

console.log(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
console.log(maxSequence([1, 5, 9, 1]))
console.log(maxSequence([-1, -2, -3, -4]))