Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Understanding the Algorithm
The solution uses a prefix sum approach with an index mapping technique. It tracks cumulative sums and uses an array to store the first occurrence of each sum value, allowing efficient calculation of subarray lengths.
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;
// Initialize the sumindex array with marker values
for(let i = 0; i < length * 2; i++){
sumindex[i] = marker;
}
for(let i = 0; i < arr.length; i++){
sum += arr[i];
// If sum is non-negative, entire prefix is valid
if (sum >= 0)
maxslice = i + 1;
// If we've seen this sum before, calculate subarray length
else if (sumindex[sum + length] != marker)
maxslice = Math.max(maxslice, i - sumindex[sum + length]);
// First time seeing this sum, store its index
else
sumindex[sum + length] = i;
}
return maxslice;
};
console.log(longestPositiveSum(arr));
Output
5
How It Works
The algorithm works by:
- Prefix Sum Tracking: Maintains a running sum of elements from the start
- Index Mapping: Uses an array to store the first occurrence of each sum value
-
Offset Handling: Adds
lengthto negative sums to use them as valid array indices - Length Calculation: When a sum repeats, the subarray between occurrences has sum zero or positive
Step-by-Step Example
const arr = [-1, -1, 0, 1, 1];
// Trace through the algorithm
let sum = 0, maxslice = 0;
console.log("Index | Element | Sum | Action");
console.log("------|---------|-----|--------");
for(let i = 0; i < arr.length; i++){
sum += arr[i];
console.log(`${i} | ${arr[i]} | ${sum} | ${sum >= 0 ? 'Update max to ' + (i + 1) : 'Check previous occurrence'}`);
if (sum >= 0) {
maxslice = i + 1;
}
}
console.log(`\nLongest non-negative sum length: ${maxslice}`);
Output
Index | Element | Sum | Action ------|---------|-----|-------- 0 | -1 | -1 | Check previous occurrence 1 | -1 | -2 | Check previous occurrence 2 | 0 | -2 | Check previous occurrence 3 | 1 | -1 | Check previous occurrence 4 | 1 | 0 | Update max to 5 Longest non-negative sum length: 5
Conclusion
This algorithm efficiently finds the longest subarray with non-negative sum using prefix sums and index tracking. It runs in O(n) time complexity, making it optimal for this problem.
