📜  只有非负元素的最大和连续子数组

📅  最后修改于: 2021-09-05 11:53:12             🧑  作者: Mango

给定一个整数数组arr[] ,任务是找到非负元素的最大总和连续子数组并返回其总和。
例子:

天真的方法:
最简单的方法是生成所有只有非负元素的子数组,同时遍历子数组并计算每个有效子数组的总和并更新最大和。
时间复杂度: O(N^2)
有效的方法:
为了优化上述方法,遍历数组,对于遇到的每个非负元素,继续计算总和。对于遇到的每个负元素,在与当前总和比较后更新最大总和。将总和重置为 0 并继续下一个元素。
下面是上述方法的实现:

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[0]);
     
    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


C++
#include 
 
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 max_so_far)
        {
            max_so_far = max_right_here;
            start = s;
            end = i;
        }
    }
 
    cout<<("Sub Array : ");
    for(int i = start; i <= end; i++)
    {
        cout<


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


输出

14

时间复杂度:O(N)

辅助空间:O(1)

更简单的方法:

C++

#include 
 
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 max_so_far)
        {
            max_so_far = max_right_here;
            start = s;
            end = i;
        }
    }
 
    cout<<("Sub Array : ");
    for(int i = start; i <= end; i++)
    {
        cout<

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);
 
    }
}
输出
Sub Array : 9 5 
Largest Sum : 14

时间复杂度:O(n)

空间复杂度:O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live