Finding the longest non-negative sum sequence using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array containing a sequence of integers, each element of which contains a possible value ranging between -1 and 1.

Our function should return the size of the longest sub-section of that sequence with a sum of zero or higher.

Example

Following is the code −

 Live Demo

const arr = [-1, -1, 0, 1, 1, -1, -1, -1];
const longestPositiveSum = (arr = []) => {
   let sum = 0;
   let maxslice = 0;
   let length = arr.length;
   const sumindex = [];
   let marker = length * 2 + 1;
   for(let i = 0; i < length * 2; i++){
      sumindex[i] = marker;
   }
   for(let i = 0; i < arr.length; i++){
      sum += arr[i];
      if (sum >= 0)
         maxslice = i + 1;
      else if (sumindex[sum+length] != marker)
         maxslice = Math.max(maxslice, i - sumindex[sum+length]);
      else
         sumindex[sum+length] = i;
   };
   return maxslice;
};
console.log(longestPositiveSum(arr));

Output

5
raja
Published on 19-Apr-2021 10:52:54
Advertisements