Given an array arr[] of N non-zero integers, the task is to find the maximum sum of the array by removing exactly one contiguous set of positive or negative elements.
Examples:
Input: arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}
Output: 4
Explanation: Maximum array sum can be obtained by removing subarray arr[0, 1] since arr[0, 1] has same type of elements i.e., negative. Thus, the required sum is 4.Input: arr[] = {2, -10, 4, 2, -8, -7}
Output: -2
Explanation: Maximum array sum can be obtained by removing subarray arr[4, 5] since arr[4, 5] has same type of elements i.e., negative. Thus, the required sum is -2.Â
Approach: The given problem can be solved based on the following observation i.e to obtain the maximum sum, a contiguous set of negative elements are to be removed since removing positive elements will reduce the array sum. However, if there are no negative elements then remove the smallest element of the array. Follow the steps to solve the problem:
- Traverse the array, arr[] and store the total sum of the array in the variable, say sum.
- Store the maximum contiguous negative sum in a variable, say max_neg.
- If there are no negative elements in the array, then update max_neg to the smallest element of an array.
- Update the value of sum to (sum – max_neg).
- Print the value of sum as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find the maximum sum of // array after removing either the contiguous // positive or negative elements void maxSum( int arr[], int n) {     // Store the total sum of array     int sum = 0; Â
    // Store the maximum contiguous     // negative sum     int max_neg = INT_MAX; Â
    // Store the sum of current     // contiguous negative elements     int tempsum = 0; Â
    // Store the minimum element of array     int small = INT_MAX; Â
    // Traverse the array, arr[]     for ( int i = 0; i < n; i++) { Â
        // Update the overall sum         sum += arr[i]; Â
        // Store minimum element of array         small = min(small, arr[i]); Â
        // If arr[i] is positive         if (arr[i] > 0) { Â
            // Update temp_sum to 0             tempsum = 0;         } Â
        else { Â
            // Add arr[i] to temp_sum             tempsum += arr[i];         } Â
        // Update max_neg         max_neg = min(max_neg, tempsum);     } Â
    // If no negative element in array     // then remove smallest positive element     if (max_neg == 0) {         max_neg = small;     } Â
    // Print the required sum     cout << sum - max_neg; } Â
// Driver Code int main() {     // Given Input     int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 };     int n = sizeof (arr) / sizeof (arr[0]); Â
    // Function Call     maxSum(arr, n); Â
    return 0; } |
Java
// Java program for the above approach import java.io.*; Â
class GFG{ Â
// Function to find the maximum sum of // array after removing either the contiguous // positive or negative elements static void maxSum( int arr[], int n) {          // Store the total sum of array     int sum = 0 ; Â
    // Store the maximum contiguous     // negative sum     int max_neg = Integer.MAX_VALUE; Â
    // Store the sum of current     // contiguous negative elements     int tempsum = 0 ; Â
    // Store the minimum element of array     int small = Integer.MAX_VALUE; Â
    // Traverse the array, arr[]     for ( int i = 0 ; i < n; i++)     {                  // Update the overall sum         sum += arr[i]; Â
        // Store minimum element of array         small = Math.min(small, arr[i]); Â
        // If arr[i] is positive         if (arr[i] > 0 )         {                          // Update temp_sum to 0             tempsum = 0 ;         }         else         {                          // Add arr[i] to temp_sum             tempsum += arr[i];         } Â
        // Update max_neg         max_neg = Math.min(max_neg, tempsum);     } Â
    // If no negative element in array     // then remove smallest positive element     if (max_neg == 0 )     {         max_neg = small;     } Â
    // Print the required sum     System.out.println(sum - max_neg); } Â
// Driver Code public static void main(String[] args) {          // Given Input     int arr[] = { - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 };     int n = arr.length; Â
    // Function Call     maxSum(arr, n); } } Â
// This code is contributed by Dharanendra L V. |
Python3
# python 3 program for the above approach Â
import sys # Function to find the maximum sum of # array after removing either the contiguous # positive or negative elements def maxSum(arr, n):        # Store the total sum of array     sum = 0 Â
    # Store the maximum contiguous     # negative sum     max_neg = sys.maxsize Â
    # Store the sum of current     # contiguous negative elements     tempsum = 0 Â
    # Store the minimum element of array     small = sys.maxsize Â
    # Traverse the array, arr[]     for i in range (n):         # Update the overall sum         sum + = arr[i] Â
        # Store minimum element of array         small = min (small, arr[i]) Â
        # If arr[i] is positive         if (arr[i] > 0 ):             # Update temp_sum to 0             tempsum = 0 Â
        else : Â
            # Add arr[i] to temp_sum             tempsum + = arr[i] Â
        # Update max_neg         max_neg = min (max_neg, tempsum) Â
    # If no negative element in array     # then remove smallest positive element     if (max_neg = = 0 ):         max_neg = small Â
    # Print the required sum     print ( sum - max_neg) Â
# Driver Code if __name__ = = '__main__' :        # Given Input     arr = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ]     n = len (arr) Â
    # Function Call     maxSum(arr, n)          # This code is contributed by bgangwar59. |
Javascript
<script> // Javascript program for the above approach Â
Â
// Function to find the maximum sum of // array after removing either the contiguous // positive or negative elements function maxSum(arr, n) {     // Store the total sum of array     let sum = 0; Â
    // Store the maximum contiguous     // negative sum     let max_neg = Number.MAX_SAFE_INTEGER; Â
    // Store the sum of current     // contiguous negative elements     let tempsum = 0; Â
    // Store the minimum element of array     let small = Number.MAX_SAFE_INTEGER; Â
    // Traverse the array, arr[]     for (let i = 0; i < n; i++) { Â
        // Update the overall sum         sum += arr[i]; Â
        // Store minimum element of array         small = Math.min(small, arr[i]); Â
        // If arr[i] is positive         if (arr[i] > 0) { Â
            // Update temp_sum to 0             tempsum = 0;         } Â
        else { Â
            // Add arr[i] to temp_sum             tempsum += arr[i];         } Â
        // Update max_neg         max_neg = Math.min(max_neg, tempsum);     } Â
    // If no negative element in array     // then remove smallest positive element     if (max_neg == 0) {         max_neg = small;     } Â
    // Print the required sum     document.write(sum - max_neg); } Â
// Driver Code Â
// Given Input let arr = [-2, -3, 4, -1, -2, 1, 5, -3]; let n = arr.length; Â
// Function Call maxSum(arr, n); Â
// This code is contributed by gfgking. </script> |
C#
// C# program for the above approach using System; Â
class GFG{ Â
// Function to find the maximum sum of // array after removing either the contiguous // positive or negative elements static void maxSum( int []arr, int n) {          // Store the total sum of array     int sum = 0; Â
    // Store the maximum contiguous     // negative sum     int max_neg = Int32.MaxValue; Â
    // Store the sum of current     // contiguous negative elements     int tempsum = 0; Â
    // Store the minimum element of array     int small = Int32.MaxValue; Â
    // Traverse the array, arr[]     for ( int i = 0; i < n; i++)     {                  // Update the overall sum         sum += arr[i]; Â
        // Store minimum element of array         small = Math.Min(small, arr[i]); Â
        // If arr[i] is positive         if (arr[i] > 0)         {                          // Update temp_sum to 0             tempsum = 0;         }         else         {                          // Add arr[i] to temp_sum             tempsum += arr[i];         } Â
        // Update max_neg         max_neg = Math.Min(max_neg, tempsum);     } Â
    // If no negative element in array     // then remove smallest positive element     if (max_neg == 0)     {         max_neg = small;     } Â
    // Print the required sum     Console.Write(sum - max_neg); } Â
// Driver Code public static void Main(String[] args) {          // Given Input     int []arr = { -2, -3, 4, -1, -2, 1, 5, -3 };     int n = arr.Length; Â
    // Function Call     maxSum(arr, n); } } Â
// This code is contributed by shivanisinghss2110 |
4
Time Complexity: O(N)
Auxiliary Space: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!