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++
// 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>
Complexity Analysis:
- Time Complexity: O(N * log N)
- Auxiliary Space: O(N)
Similar Reads
Smallest subarray with sum greater than or equal to K Given an array A[] consisting of N integers and an integer K, the task is to find the length of the smallest subarray with sum greater than or equal to K. If no such subarray exists, print -1. Examples: Input: A[] = {2, -1, 2}, K = 3 Output: 3 Explanation: Sum of the given array is 3. Hence, the sm
15+ min read
Longest Subarray with first element greater than or equal to Last Given an array of integers arr[] of size n. Your task is to find the maximum length subarray such that its first element is greater than or equals to the last element.Examples: Input : arr[] = [-5, -1, 7, 5, 1, -2]Output : 5Explanation : Subarray {-1, 7, 5, 1, -2} forms maximum length subarray with
15+ min read
Length of longest subarray with product greater than or equal to 0 Given an array arr[] of N integers, the task is to find the length of the longest subarray whose product is greater than or equals to 0.Examples: Input: arr[] = {-1, 1, 1, -2, 3, 2, -1 } Output: 6 Explanation: The longest subarray with product ? 0 = {1, 1, -2, 3, 2, -1} and {-1, 1, 1, -2, 3, 2}. Len
6 min read
Longest subarray having average greater than or equal to x Given an array of integers and an integer x. Find the length of maximum size subarray having an average of integers greater than or equal to x.Examples: Input : arr[] = {-2, 1, 6, -3}, x = 3Output : 2Longest subarray is {1, 6} having average3.5 greater than x = 3.Input : arr[] = {2, -3, 3, 2, 1}, x
14 min read
Find the longest Subarray with equal Sum and Product Given an array arr[] of N integers, the task is to find the length of the longest subarray where the sum of the elements in the subarray is equal to the product of the elements in the subarray. Examples: Input: arr[] = [1, 2, 1, 2, 2, 5, 6, 24]Output: 5Explanation: The subarray [1, 2, 1, 2, 2] has a
11 min read