Largest sum contiguous subarray having only non-negative elements

02 Mar, 2022
Given an integer array arr[], the task is to find the largest sum contiguous subarray of non-negative elements and return its sum.
Examples: 
Input: arr[] = {1, 4, -3, 9, 5, -6} Output: 14 Explanation: Subarray [9, 5] is the subarray having maximum sum with all non-negative elements.
Input: arr[] = {12, 0, 10, 3, 11} Output: 36  
Naive Approach: The simplest approach is to generate all subarrays having only non-negative elements while traversing the subarray and calculating the sum of every valid subarray and updating the maximum sum. 
Time Complexity: O(N^2)
Efficient Approach: To optimize the above approach, traverse the array, and for every non-negative element encountered, keep calculating the sum. For every negative element encountered, update the maximum sum after comparison with the current sum. Reset the sum to 0 and proceed to the next element.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return Largest Sum Contiguous// Subarray having non-negative numberint maxNonNegativeSubArray(int A[], int N){         // Length of given array    int l = N;     int sum = 0, i = 0;    int Max = -1;     // Traversing array    while (i < l)    {                 // Increment i counter to avoid        // negative elements        while (i < l && A[i] < 0)        {            i++;            continue;        }         // Calculating sum of contiguous        // subarray of non-negative        // elements        while (i < l && 0 <= A[i])        {            sum += A[i++];             // Update the maximum sum            Max = max(Max, sum);        }         // Reset sum        sum = 0;    }     // Return the maximum sum    return Max;} // Driver codeint main(){    int arr[] = { 1, 4, -3, 9, 5, -6 };         int N = sizeof(arr) / sizeof(arr[0]);         cout << maxNonNegativeSubArray(arr, N);    return 0;} // This code is contributed by divyeshrabadiya07
// Java program to implement// the above approachimport java.util.*; class GFG {     // Function to return Largest Sum Contiguous    // Subarray having non-negative number    static int maxNonNegativeSubArray(int[] A)    {        // Length of given array        int l = A.length;         int sum = 0, i = 0;         int max = -1;         // Traversing array        while (i < l) {             // Increment i counter to avoid            // negative elements            while (i < l && A[i] < 0) {                i++;                continue;            }             // Calculating sum of contiguous            // subarray of non-negative            // elements            while (i < l && 0 <= A[i]) {                 sum += A[i++];                 // Update the maximum sum                max = Math.max(max, sum);            }             // Reset sum            sum = 0;        }         // Return the maximum sum        return max;    }     // Driver Code    public static void main(String[] args)    {         int[] arr = { 1, 4, -3, 9, 5, -6 };         System.out.println(maxNonNegativeSubArray(            arr));    }}
# Python3 program for the above approachimport math # Function to return Largest Sum Contiguous# Subarray having non-negative numberdef maxNonNegativeSubArray(A, N):         # Length of given array    l = N         sum = 0    i = 0    Max = -1     # Traversing array    while (i < l):                 # Increment i counter to avoid        # negative elements        while (i < l and A[i] < 0):            i += 1            continue                 # Calculating sum of contiguous        # subarray of non-negative        # elements        while (i < l and 0 <= A[i]):            sum += A[i]            i += 1                         # Update the maximum sum            Max = max(Max, sum)                 # Reset sum        sum = 0;         # Return the maximum sum    return Max     # Driver codearr = [ 1, 4, -3, 9, 5, -6 ] # Length of arrayN = len(arr) print(maxNonNegativeSubArray(arr, N)) # This code is contributed by sanjoy_62   
// C# program to implement// the above approachusing System; class GFG{ // Function to return Largest Sum Contiguous// Subarray having non-negative numberstatic int maxNonNegativeSubArray(int[] A){         // Length of given array    int l = A.Length;     int sum = 0, i = 0;    int max = -1;     // Traversing array    while (i < l)    {                 // Increment i counter to avoid        // negative elements        while (i < l && A[i] < 0)        {            i++;            continue;        }         // Calculating sum of contiguous        // subarray of non-negative        // elements        while (i < l && 0 <= A[i])        {            sum += A[i++];                         // Update the maximum sum            max = Math.Max(max, sum);        }         // Reset sum        sum = 0;    }     // Return the maximum sum    return max;} // Driver Codepublic static void Main(){    int[] arr = { 1, 4, -3, 9, 5, -6 };     Console.Write(maxNonNegativeSubArray(arr));}} // This code is contributed by chitranayal
<script> // Javascript program to implement// the above approach // Function to return Largest Sum Contiguous// Subarray having non-negative numberfunction maxNonNegativeSubArray(A, N){         // Length of given array    var l = N;     var sum = 0, i = 0;    var Max = -1;     // Traversing array    while (i < l)    {                 // Increment i counter to avoid        // negative elements        while (i < l && A[i] < 0)        {            i++;            continue;        }         // Calculating sum of contiguous        // subarray of non-negative        // elements        while (i < l && 0 <= A[i])        {            sum += A[i++];             // Update the maximum sum            Max = Math.max(Max, sum);        }         // Reset sum        sum = 0;    }     // Return the maximum sum    return Max;} // Driver codevar arr = [1, 4, -3, 9, 5, -6];var N = arr.length;document.write( maxNonNegativeSubArray(arr, N)); // This code is contributed by famously.</script>
14
Time Complexity: O(N)
Auxiliary Space: O(1)
C++
Java
Python3
C#
Javascript
#include <iostream> using namespace std; int main(){    int arr[] = { 1, 4, -3, 9, 5, -6 };    int n = sizeof(arr) / sizeof(arr[0]);    int max_so_far = 0, max_right_here = 0;    int start = 0, end = 0, s = 0;    for (int i = 0; i < n; i++) {        if (arr[i] < 0) {            s = i + 1;            max_right_here = 0;        }        else {            max_right_here += arr[i];        }         if (max_right_here > max_so_far) {            max_so_far = max_right_here;            start = s;            end = i;        }    }     cout << ("Sub Array : ");    for (int i = start; i <= end; i++) {        cout << arr[i] << " ";    }     cout << endl;    cout << "Largest Sum : " << max_so_far;} // This code is contributed by SoumikMondal
import java.util.*; class GFG{ public static void main(String[] args){    int arr[] = { 1, 4, -3, 9, 5, -6 };    int n = arr.length;    int max_so_far = 0, max_right_here = 0;    int start = 0, end = 0, s = 0;    for (int i = 0; i < n; i++) {        if (arr[i] < 0) {            s = i + 1;            max_right_here = 0;        }        else {            max_right_here += arr[i];        }         if (max_right_here > max_so_far) {            max_so_far = max_right_here;            start = s;            end = i;        }    }     System.out.print("Sub Array : ");    for (int i = start; i <= end; i++) {        System.out.print( arr[i]);        System.out.print(" ");    }    System.out.println();    System.out.print("Largest Sum : ");    System.out.print( max_so_far);} } // This code is contributed by amreshkumar3.
arr = [1, 4, -3, 9, 5, -6]n = len(arr)max_so_far = 0max_right_here = 0start = 0end = 0s = 0for i in range(0, n):    if arr[i] < 0:        s = i + 1        max_right_here = 0    else:        max_right_here += arr[i]     if max_right_here > max_so_far:        max_so_far = max_right_here        start = s        end = i print("Sub Array : ")for i in range(start, end + 1):    print(arr[i], end=" ")print()print("largest sum=", max_so_far) # This code is contributed by amreshkumar3.
using System; public class GFG {   public static void Main(String[] args)  {    int[] arr = { 1, 4, -3, 9, 5, -6 };    int n = arr.Length;    int max_so_far = 0, max_right_here = 0;    int start = 0, end = 0, s = 0;    for (int i = 0; i < n; i++) {      if (arr[i] < 0) {        s = i + 1;        max_right_here = 0;      }      else {        max_right_here += arr[i];      }       if (max_right_here > max_so_far) {        max_so_far = max_right_here;        start = s;        end = i;      }    }     Console.Write("Sub Array : ");    for (int i = start; i <= end; i++) {      Console.Write(arr[i]);      Console.Write(" ");    }    Console.WriteLine();    Console.Write("Largest Sum : ");    Console.Write(max_so_far);  }} // This code is contributed by umadevi9616
<script> let arr = [ 1, 4, -3, 9, 5, -6 ];let n = arr.length;let max_so_far = 0, max_right_here = 0;let start = 0, end = 0, s = 0;for(let i = 0; i < n; i++){    if (arr[i] < 0)    {        s = i + 1;        max_right_here = 0;    }    else    {        max_right_here += arr[i];    }     if (max_right_here > max_so_far)    {        max_so_far = max_right_here;        start = s;        end = i;    }} // Driver codedocument.write("Sub Array : ");for(let i = start; i <= end; i++){    document.write(arr[i] + " ");} document.write("<br>");document.write("Largest Sum : " + max_so_far); // This code is contributed by Potta Lokesh </script>
Sub Array : 9 5 
Largest Sum : 14
Time Complexity: O(n)
Space complexity: O(1)
divyeshrabadiya07
sanjoy_62
ukasp
mriduldas0226
famously
SoumikMondal
lokeshpotta20
kushsharma1001
amreshkumar3
umadevi9616
subarray
subarray-sum
Arrays
Competitive Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.