SOURCE

function longestConsecutive(numArr) {
  const numSet = new Set();
  for(let item of numArr) {
    numSet.add(item);
  }
  let maxSum = 0;
  for (let i = 0; i < numArr.length; i ++) {
    if (!numSet.has(numArr[i] - 1)) {
      let currentNum = numArr[i];
      let currentMaxSum = currentNum;

      while (numSet.has(currentNum + 1)) {
        currentMaxSum = currentMaxSum + currentNum + 1;
        currentNum += 1;
      }

      maxSum = Math.max(maxSum, currentMaxSum);
    }
    
  }
  return maxSum;
}

console.log(longestConsecutive([1,3,-5,4,5,-4,6]));
console 命令行工具 X clear

                    
>
console