Longest Subarray with Sum greater than Equal to Zero - GeeksforGeeks

19 May, 2021
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. 
Below is the implementation of the above approach.  
C++
Java
Python3
C#
PHP
Javascript
// 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 subarrayint 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 subarrayint 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 Codeint main(){    int a[] = { -1, 4, -2, -5, 6, -8 };     int n = sizeof(a) / sizeof(a[0]);     cout << longestSubarray(a, n);     return 0;}
// 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 subarraystatic 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 subarraystatic 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 program to compute the longest# with sum greater than equal to 0import math as mt # function for the searching the# starting index of the subarraydef 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 subarraydef 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 Codea = [-1, 4, -2, -5, 6, -8]  n = len(a)print(longestSubarray(a, n)) # This code is contributed# by Mohit kumar 29
// 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 subarraystatic 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 subarraystatic 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 Program to compute the// longest subarray with// sum greater than equal to 0. // Function for the searching the// starting index of the subarrayfunction 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 subarrayfunction 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?>
<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>
5
 
Time Complexity: O(N * log N) Auxiliary Space: O(N)  
Shivi_Aggarwal
Shashank12
ukasp
mohit kumar 29
rag2127
Binary Search
subarray
Technical Scripter 2018
Arrays
Technical Scripter
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times
Queue | Set 1 (Introduction and Array Implementation)