Longest Subarray with Sum greater than Equal to Zero
Last Updated :
02 Sep, 2022
Given an array of N integers. The task is to find the maximum length subarray such that the sum of all its elements is greater than or equal to 0.
Examples:
Input: arr[]= {-1, 4, -2, -5, 6, -8}
Output: 5
Explanation: {-1, 4, -2, -5, 6} forms the longest subarray with sum=2.
Input: arr[]={-5, -6}
Output: 0
Explanation: No such subarray is possible
A Naive Approach is to pre-calculate the prefix sum of the array. Then use two nested loops for every starting and ending index and if the prefix sum till the ending index is minus the prefix sum before the starting index is greater than equal to 0, then update the answer accordingly.
Time Complexity: O(N2)
An efficient approach is to use Binary search to solve the following problem. Below are the steps to solve the above problem:
- First, calculate the suffix sum to every index of the array and store it in another array.
- Use another array search space to store the starting points for every subarray.
- Iterate from 0’th index and if the suffix till that i’th index is greater than the topmost element in the search space, add that suffix sum to the search space.
- Use binary search to find the lowest index in the search space such that the suffix sum till that index minus the suffix sum till (i+1)’th is greater than equal to 0. If any such index exists, then update the answer accordingly.
The key observation here is that add a suffix sum to the search space if it is greater than all the other suffix sums in the search space since the length has to be maximized.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int search( int * searchspace, int s, int e, int key)
{
int ans = -1;
while (s <= e) {
int mid = (s + e) / 2;
if (searchspace[mid] - key >= 0) {
ans = mid;
e = mid - 1;
}
else {
s = mid + 1;
}
}
return ans;
}
int longestSubarray( int a[], int n)
{
int SuffixSum[n + 1];
SuffixSum[n] = 0;
for ( int i = n - 1; i >= 0; --i) {
SuffixSum[i] = SuffixSum[i + 1] + a[i];
}
int ans = 0;
int searchspace[n];
int index[n];
int j = 0;
for ( int i = 0; i < n; ++i) {
if (j == 0 or SuffixSum[i] > searchspace[j - 1]) {
searchspace[j] = SuffixSum[i];
index[j] = i;
j++;
}
int idx = search(searchspace, 0, j - 1, SuffixSum[i + 1]);
if (idx != -1)
ans = max(ans, i - index[idx] + 1);
}
return ans;
}
int main()
{
int a[] = { -1, 4, -2, -5, 6, -8 };
int n = sizeof (a) / sizeof (a[0]);
cout << longestSubarray(a, n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int search( int searchspace[], int s, int e, int key)
{
int ans = - 1 ;
while (s <= e) {
int mid = (s + e) / 2 ;
if (searchspace[mid] - key >= 0 ) {
ans = mid;
e = mid - 1 ;
}
else {
s = mid + 1 ;
}
}
return ans;
}
static int longestSubarray( int []a, int n)
{
int SuffixSum[] = new int [n+ 1 ];
SuffixSum[n] = 0 ;
for ( int i = n - 1 ; i >= 0 ; --i) {
SuffixSum[i] = SuffixSum[i + 1 ] + a[i];
}
int ans = 0 ;
int searchspace[] = new int [n];
int index[] = new int [n];
int j = 0 ;
for ( int i = 0 ; i < n; ++i) {
if ((j == 0 ) || SuffixSum[i] > searchspace[j - 1 ]) {
searchspace[j] = SuffixSum[i];
index[j] = i;
j++;
}
int idx = search(searchspace, 0 , j - 1 , SuffixSum[i + 1 ]);
if (idx != - 1 )
ans = Math.max(ans, i - index[idx] + 1 );
}
return ans;
}
public static void main (String[] args) {
int []a = { - 1 , 4 , - 2 , - 5 , 6 , - 8 };
int n = a.length;
System.out.println(longestSubarray(a, n));
}
}
|
Python3
import math as mt
def search(searchspace, s, e, key):
ans = - 1
while s < = e:
mid = (s + e) / / 2
if searchspace[mid] - key > = 0 :
ans = mid
e = mid - 1
else :
s = mid + 1
return ans
def longestSubarray(a, n):
SuffixSum = [ 0 for i in range (n + 1 )]
for i in range (n - 1 , - 1 , - 1 ):
SuffixSum[i] = SuffixSum[i + 1 ] + a[i]
ans = 0
searchspace = [ 0 for i in range (n)]
index = [ 0 for i in range (n)]
j = 0
for i in range (n):
if j = = 0 or (SuffixSum[i] >
searchspace[j - 1 ]):
searchspace[j] = SuffixSum[i]
index[j] = i
j + = 1
idx = search(searchspace, 0 , j - 1 ,
SuffixSum[i + 1 ])
if idx ! = - 1 :
ans = max (ans, i - index[idx] + 1 )
return ans
a = [ - 1 , 4 , - 2 , - 5 , 6 , - 8 ]
n = len (a)
print (longestSubarray(a, n))
|
C#
using System;
class GFG {
static int search( int [] searchspace, int s, int e, int key)
{
int ans = -1;
while (s <= e) {
int mid = (s + e) / 2;
if (searchspace[mid] - key >= 0) {
ans = mid;
e = mid - 1;
}
else {
s = mid + 1;
}
}
return ans;
}
static int longestSubarray( int [] a, int n)
{
int [] SuffixSum = new int [n+1];
SuffixSum[n] = 0;
for ( int i = n - 1; i >= 0; --i) {
SuffixSum[i] = SuffixSum[i + 1] + a[i];
}
int ans = 0;
int [] searchspace = new int [n];
int [] index = new int [n];
int j = 0;
for ( int i = 0; i < n; ++i) {
if ((j == 0) || SuffixSum[i] > searchspace[j - 1]) {
searchspace[j] = SuffixSum[i];
index[j] = i;
j++;
}
int idx = search(searchspace, 0, j - 1, SuffixSum[i + 1]);
if (idx != -1)
ans = Math.Max(ans, i - index[idx] + 1);
}
return ans;
}
public static void Main () {
int [] a = { -1, 4, -2, -5, 6, -8 };
int n = a.Length;
Console.Write(longestSubarray(a, n));
}
}
|
PHP
<?php
function search( $searchspace , $s ,
$e , $key )
{
$ans = -1;
while ( $s <= $e )
{
$mid = ( $s + $e ) / 2;
if ( $searchspace [ $mid ] - $key >= 0)
{
$ans = $mid ;
$e = $mid - 1;
}
else
{
$s = $mid + 1;
}
}
return $ans ;
}
function longestSubarray(& $a , $n )
{
$SuffixSum [ $n ] = 0;
for ( $i = $n - 1; $i >= 0; -- $i )
{
$SuffixSum [ $i ] = $SuffixSum [ $i + 1] +
$a [ $i ];
}
$ans = 0;
$j = 0;
for ( $i = 0; $i < $n ; ++ $i )
{
if ( $j == 0 or $SuffixSum [ $i ] >
$searchspace [ $j - 1])
{
$searchspace [ $j ] = $SuffixSum [ $i ];
$index [ $j ] = $i ;
$j ++;
}
$idx = search( $searchspace , 0, $j - 1,
$SuffixSum [ $i + 1]);
if ( $idx != -1)
$ans = max( $ans , $i -
$index [ $idx ] + 1);
}
return $ans ;
}
$a = array (-1, 4, -2, -5, 6, -8 );
$n = sizeof( $a );
echo (longestSubarray( $a , $n ));
?>
|
Javascript
<script>
function search(searchspace,s,e,key)
{
let ans = -1;
while (s <= e) {
let mid = Math.floor((s + e) / 2);
if (searchspace[mid] - key >= 0) {
ans = mid;
e = mid - 1;
}
else {
s = mid + 1;
}
}
return ans;
}
function longestSubarray(a,n)
{
let SuffixSum = new Array(n+1);
SuffixSum[n] = 0;
for (let i = n - 1; i >= 0; --i) {
SuffixSum[i] = SuffixSum[i + 1] + a[i];
}
let ans = 0;
let searchspace = new Array(n);
let index = new Array(n);
let j = 0;
for (let i = 0; i < n; ++i) {
if ((j == 0) || SuffixSum[i] > searchspace[j - 1]) {
searchspace[j] = SuffixSum[i];
index[j] = i;
j++;
}
let idx = search(searchspace, 0, j - 1, SuffixSum[i + 1]);
if (idx != -1)
ans = Math.max(ans, i - index[idx] + 1);
}
return ans;
}
let a=[-1, 4, -2, -5, 6, -8];
let n = a.length;
document.write(longestSubarray(a, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(N * log N)
- Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...