# Finding the longest non-negative sum sequence using JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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
Updated on 19-Apr-2021 10:56:55