Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the longest non-negative sum sequence using JavaScript
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 −
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
Advertisements