Related Articles
Largest sum contiguous subarray having only non-negative elements
• Difficulty Level : Medium
• Last Updated : 18 May, 2021

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

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Function to return Largest Sum Contiguous``// Subarray having non-negative number``int` `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 code``int` `main()``{``    ``int` `arr[] = { 1, 4, -3, 9, 5, -6 };``    ` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ` `    ``cout << maxNonNegativeSubArray(arr, N);``    ``return` `0;``}` `// This code is contributed by divyeshrabadiya07`

## Java

 `// Java program to implement``// the above approach``import` `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

 `# Python3 program for the above approach``import` `math` `# Function to return Largest Sum Contiguous``# Subarray having non-negative number``def` `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 code``arr ``=` `[ ``1``, ``4``, ``-``3``, ``9``, ``5``, ``-``6` `]` `# Length of array``N ``=` `len``(arr)` `print``(maxNonNegativeSubArray(arr, N))` `# This code is contributed by sanjoy_62   `

## C#

 `// C# program to implement``// the above approach``using` `System;` `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()``{``    ``int``[] arr = { 1, 4, -3, 9, 5, -6 };` `    ``Console.Write(maxNonNegativeSubArray(arr));``}``}` `// This code is contributed by chitranayal`

## Javascript

 ``
Output

`14`

Time Complexity: O(N)

Auxiliary Space : O(1)

## Java

 `public` `class` `maxNonNegativeSubArray {``    ` `    ``public` `static` `void` `main (String[] args) ``throws` `java.lang.Exception{`  `        ``int``[] arr = {``1``, ``4``, -``3``, ``9``, ``5``, -``6``};``        ``int` `max_so_far=``0``, max_right_here = ``0``;``        ``int` `start = ``0``, end = ``0``, s=``0``;`  `        ``for``(``int` `i=``0``; i 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.println();``        ``System.out.print(``"Largest Sum : "` `+ max_so_far);` `    ``}``}`
Output
```Sub Array : 9 5
Largest Sum : 14```

Time Complexity: O(n)

Space complexity: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up