Largest sum contiguous subarray having only non-negative elements

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement 
// the above approach 
#include <bits/stdc++.h>
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[0]);
      
    cout << maxNonNegativeSubArray(arr, N);
    return 0;
}
  
// This code is contributed by divyeshrabadiya07
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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    
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
chevron_right

Output:
14

Time Complexity: O(N)

Auxiliary Space : O(1)





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :