Open In App

Longest Subarray with Sum greater than Equal to Zero

Last Updated : 02 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to compute the
// longest subarray with
// sum greater than equal to 0.
#include <bits/stdc++.h>
using namespace std;
 
// Function for the searching the
// starting index of the subarray
int search(int* searchspace, int s, int e, int key)
{
    // -1 signifies that no
    // starting point of the subarray
    // is not found with sum greater
    // than equal to 0.
    int ans = -1;
 
    // Binary search
    while (s <= e) {
        int mid = (s + e) / 2;
 
        if (searchspace[mid] - key >= 0) {
            ans = mid;
            e = mid - 1;
        }
        else {
            s = mid + 1;
        }
    }
 
    return ans;
}
 
// Function to return the longest subarray
int longestSubarray(int a[], int n)
{
    // Array for the suffix sum
    // of the above the array.
    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;
 
    // Search Space for potential starting
    // points of the subarray.
    // It will store the suffix sum
    // till i'th index in increasing order.
    int searchspace[n];
 
    // It will store the indexes
    // till which the suffix sum
    // is present in search space.
    int index[n];
 
    int j = 0;
 
    for (int i = 0; i < n; ++i) {
 
        // add the element to the search space if the j=0
        // or if the topmost element is lesser
        // than present suffix sum.
        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]);
 
        // Only when idx is not -1 an subarray is
        // possible with ending index at i.
        if (idx != -1)
            ans = max(ans, i - index[idx] + 1);
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    int a[] = { -1, 4, -2, -5, 6, -8 };
 
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << longestSubarray(a, n);
 
    return 0;
}


Java




// Java  Program to compute the
// longest subarray with
// sum greater than equal to 0.
 
import java.io.*;
 
class GFG {
 
 
// Function for the searching the
// starting index of the subarray
static int search(int searchspace[], int s, int e, int key)
{
    // -1 signifies that no
    // starting point of the subarray
    // is not found with sum greater
    // than equal to 0.
    int ans = -1;
 
    // Binary search
    while (s <= e) {
        int mid = (s + e) / 2;
 
        if (searchspace[mid] - key >= 0) {
            ans = mid;
            e = mid - 1;
        }
        else {
            s = mid + 1;
        }
    }
 
    return ans;
}
 
// Function to return the longest subarray
static int longestSubarray(int []a, int n)
{
    // Array for the suffix sum
    // of the above the array.
    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;
 
    // Search Space for potential starting
    // points of the subarray.
    // It will store the suffix sum
    // till i'th index in increasing order.
    int searchspace[] = new int[n];
 
    // It will store the indexes
    // till which the suffix sum
    // is present in search space.
    int index[] = new int[n];
 
    int j = 0;
 
    for (int i = 0; i < n; ++i) {
 
        // add the element to the search space if the j=0
        // or if the topmost element is lesser
        // than present suffix sum.
        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]);
 
        // Only when idx is not -1 an subarray is
        // possible with ending index at i.
        if (idx != -1)
            ans = Math.max(ans, i - index[idx] + 1);
    }
 
    return ans;
}
 
// Driver Code
 
 
    public static void main (String[] args) {
            int []a = { -1, 4, -2, -5, 6, -8 };
 
    int n = a.length;
 
    System.out.println(longestSubarray(a, n));
    }
}
// This code is contributed
// by  anuj_67..


Python3




# Python3 program to compute the longest
# with sum greater than equal to 0
import math as mt
 
# function for the searching the
# starting index of the subarray
def search(searchspace, s, e, key):
     
    # -1 signifies that no starting point
    # of the subarray is not found with
    # sum greater than equal to 0.
     
    ans = -1
     
    # Binary search
    while s <= e:
        mid = (s + e) // 2
         
        if searchspace[mid] - key >= 0:
            ans = mid
            e = mid - 1
        else:
            s = mid + 1
    return ans
     
# function to return the longest subarray
def longestSubarray(a, n):
    # Array for the suffix sum of
    # the above the array
    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
     
    # Search Space for potential starting
    # points of the subarray.
    # It will store the suffix sum
    # till i'th index in increasing order
    searchspace = [0 for i in range(n)]
     
    # It will store the indexes
    # till which the suffix sum
    # is present in search space
    index = [0 for i in range(n)]
     
    j = 0
     
    for i in range(n):
         
        # add the element to the search space
        # if the j=0 or if the topmost element
        # is lesser than present suffix sum
        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])
                      
        # Only when idx is not -1 an subarray is
        # possible with ending index at i.
        if idx != -1:
            ans = max(ans, i - index[idx] + 1)
     
    return ans
 
# Driver Code
a = [-1, 4, -2, -5, 6, -8]
  
n = len(a)
print(longestSubarray(a, n))
 
# This code is contributed
# by Mohit kumar 29


C#




// C#  Program to compute the
// longest subarray with
// sum greater than equal to 0.
  
using System;
  
class GFG {
  
// Function for the searching the
// starting index of the subarray
static int search(int[] searchspace, int s, int e, int key)
{
    // -1 signifies that no
    // starting point of the subarray
    // is not found with sum greater
    // than equal to 0.
    int ans = -1;
  
    // Binary search
    while (s <= e) {
        int mid = (s + e) / 2;
  
        if (searchspace[mid] - key >= 0) {
            ans = mid;
            e = mid - 1;
        }
        else {
            s = mid + 1;
        }
    }
  
    return ans;
}
  
// Function to return the longest subarray
static int longestSubarray(int[] a, int n)
{
    // Array for the suffix sum
    // of the above the array.
    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;
  
    // Search Space for potential starting
    // points of the subarray.
    // It will store the suffix sum
    // till i'th index in increasing order.
    int[] searchspace = new int[n];
  
    // It will store the indexes
    // till which the suffix sum
    // is present in search space.
    int[] index = new int[n];
  
    int j = 0;
  
    for (int i = 0; i < n; ++i) {
  
        // add the element to the search space if the j=0
        // or if the topmost element is lesser
        // than present suffix sum.
        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]);
  
        // Only when idx is not -1 an subarray is
        // possible with ending index at i.
        if (idx != -1)
            ans = Math.Max(ans, i - index[idx] + 1);
    }
  
    return ans;
}
  
// Driver Code
  
  
    public static void Main () {
            int[] a = { -1, 4, -2, -5, 6, -8 };
  
    int n = a.Length;
  
    Console.Write(longestSubarray(a, n));
    }
}


PHP




<?php
// PHP Program to compute the
// longest subarray with
// sum greater than equal to 0.
 
// Function for the searching the
// starting index of the subarray
function search($searchspace, $s,
                $e, $key)
{
    // -1 signifies that no starting
    // point of the subarray is not
    // found with sum greater than 
    // equal to 0.
    $ans = -1;
 
    // Binary search
    while ($s <= $e)
    {
        $mid = ($s + $e) / 2;
 
        if ($searchspace[$mid] - $key >= 0)
        {
            $ans = $mid;
            $e = $mid - 1;
        }
        else
        {
            $s = $mid + 1;
        }
    }
 
    return $ans;
}
 
// Function to return the
// longest subarray
function longestSubarray(&$a, $n)
{
    // Array for the suffix sum
    // of the above the array.
    $SuffixSum[$n] = 0;
 
    for ($i = $n - 1; $i >= 0; --$i)
    {
        $SuffixSum[$i] = $SuffixSum[$i + 1] +
                         $a[$i];
    }
 
    $ans = 0;
 
    // Search Space for potential
    // starting points of the subarray.
    // It will store the suffix sum
    // till i'th index in increasing order.
 
    // It will store the indexes
    // till which the suffix sum
    // is present in search space.
    $j = 0;
 
    for ($i = 0; $i < $n; ++$i)
    {
 
        // add the element to the search
        // space if the j=0 or if the
        // topmost element is lesser
        // than present suffix sum.
        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]);
 
        // Only when idx is not -1 an
        // subarray is possible with
        // ending index at i.
        if ($idx != -1)
            $ans = max($ans, $i -
                       $index[$idx] + 1);
    }
 
    return $ans;
}
 
// Driver Code
$a = array(-1, 4, -2, -5, 6, -8 );
$n = sizeof($a);
echo (longestSubarray($a, $n));
 
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript




<script>
// Javascript  Program to compute the
// longest subarray with
// sum greater than equal to 0.
     
// Function for the searching the
// starting index of the subarray
    function search(searchspace,s,e,key)
    {
        // -1 signifies that no
        // starting point of the subarray
        // is not found with sum greater
        // than equal to 0.
        let ans = -1;
   
        // Binary search
        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 to return the longest subarray
    function longestSubarray(a,n)
    {
        // Array for the suffix sum
        // of the above the array.
        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;
   
        // Search Space for potential starting
        // points of the subarray.
        // It will store the suffix sum
        // till i'th index in increasing order.
        let searchspace = new Array(n);
   
        // It will store the indexes
        // till which the suffix sum
        // is present in search space.
        let index = new Array(n);
   
        let j = 0;
   
        for (let i = 0; i < n; ++i) {
   
        // add the element to the search space if the j=0
        // or if the topmost element is lesser
        // than present suffix sum.
            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]);
   
        // Only when idx is not -1 an subarray is
        // possible with ending index at i.
            if (idx != -1)
                ans = Math.max(ans, i - index[idx] + 1);
        }
   
        return ans;
    }
     
    // Driver Code
    let a=[-1, 4, -2, -5, 6, -8];
    let n = a.length;
    document.write(longestSubarray(a, n));
         
 
 
// This code is contributed by rag2127
</script>


Output

5

Complexity Analysis:

  • Time Complexity: O(N * log N) 
  • Auxiliary Space: O(N) 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads