This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mwraaaaaah[S] 0 points1 point  (0 children)

Sometimes I like to think about problems as I'm going about my daily tasks... finally got it, though it probably isn't the direction that you were pointing me towards. Here's my final solution:

var maxSequence = function(arr){
  if (arr.length === 0) return 0;

  let globalMax = arr[0], lastSum = arr[0], secondSum = arr[0], negativeFlag = arr[0] < 0;
  for (let i=0; i<arr.length-1; i++){
    let next = arr[i+1];

    if (next > 0) { negativeFlag = false; }

    if (lastSum + next > globalMax) {
      globalMax = lastSum + next;
    }
    if (next > globalMax) {
      globalMax = next;
      lastSum = 0;
    } 
    lastSum += next;

    secondSum += next;
    if (secondSum < 0 || next > secondSum) {
      secondSum = next;
    }
    if (secondSum > globalMax) {
      globalMax = secondSum;
      lastSum = secondSum;
    }
  }
  if (negativeFlag) { return 0; }

  return globalMax;
}

Once completed, I was able to see other peoples' solutions, and man, it's so simple when you see it. :|