Maximum sum subarray removing at most one element

Given an array, we need to find maximum sum subarray, removing one element is also allowed to get the maximum sum.

Examples :

Input  : arr[] = {1, 2, 3, -4, 5}
Output : 11
Explanation : We can get maximum sum subarray by
removing -4.

Input  : arr[] = [-2, -3, 4, -1, -2, 1, 5, -3]
Output : 9
Explanation : We can get maximum sum subarray by
removing -2 as, [4, -1, 1, 5] summing 9, which is 
the maximum achievable sum.



If element removal condition is not applied, we can solve this problem using Kadane’s algorithm but here one element can be removed also for increasing maximum sum. This condition can be handled using two arrays, forward and backward array, these arrays store the current maximum subarray sum from starting to ith index, and from ith index to ending respectively.
In below code, two loops are written, first one stores maximum current sum in forward direction in fw[] and other loop stores the same in backward direction in bw[]. Getting current maximum and updation is same as Kadane’s algorithm.
Now when both arrays are created, we can use them for one element removal conditions as follows, at each index i, maximum subarray sum after ignoring i’th element will be fw[i-1] + bw[i+1] so we loop for all possible i values and we choose maximum among them.
Total time complexity and space complexity of solution is O(N)

C/C++

// C++ program to get maximum sum subarray removing
// at-most one element
#include <bits/stdc++.h>
using namespace std;
  
// Method returns maximum sum of all subarray where
// removing one element is also allowed
int maxSumSubarrayRemovingOneEle(int arr[], int n)
{
    // Maximum sum subarrays in forward and backward
    // directions
    int fw[n], bw[n];
  
    // Initialize current max and max so far.
    int cur_max = arr[0], max_so_far = arr[0];
  
    // calculating maximum sum subarrays in forward
    // direction
    fw[0] = arr[0];
    for (int i = 1; i < n; i++)
    {
        cur_max = max(arr[i], cur_max + arr[i]);
        max_so_far = max(max_so_far, cur_max);
  
        // storing current maximum till ith, in
        // forward array
        fw[i] = cur_max;
    }
  
    // calculating maximum sum subarrays in backward
    // direction
    cur_max = max_so_far = bw[n-1] = arr[n-1];
    for (int i = n-2; i >= 0; i--)
    {
        cur_max = max(arr[i], cur_max + arr[i]);
        max_so_far = max(max_so_far, cur_max);
  
        // storing current maximum from ith, in
        // backward array
        bw[i] = cur_max;
    }
  
    /*  Initializing final ans by max_so_far so that,
        case when no element is removed to get max sum
        subarray is also handled  */
    int fans = max_so_far;
  
    //  choosing maximum ignoring ith element
    for (int i = 1; i < n - 1; i++)
        fans = max(fans, fw[i - 1] + bw[i + 1]);
  
    return fans;
}
  
//  Driver code to test above methods
int main()
{
    int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxSumSubarrayRemovingOneEle(arr, n);
    return 0;
}

Java

// Java program to get maximum sum subarray 
// removing at-most one element
class GFG {
      
    // Method returns maximum sum of all subarray where
    // removing one element is also allowed
    static int maxSumSubarrayRemovingOneEle(int arr[], 
                                                 int n)
    {
          
        // Maximum sum subarrays in forward and 
        // backward directions
        int fw[] = new int[n];
        int bw[] = new int[n];
  
        // Initialize current max and max so far.
        int cur_max = arr[0], max_so_far = arr[0];
  
        // calculating maximum sum subarrays in forward
        // direction
        fw[0] = arr[0];
  
        for (int i = 1; i < n; i++) {
  
            cur_max = Math.max(arr[i], cur_max + arr[i]);
            max_so_far = Math.max(max_so_far, cur_max);
  
            // storing current maximum till ith, in
            // forward array
            fw[i] = cur_max;
        }
  
        // calculating maximum sum subarrays in backward
        // direction
        cur_max = max_so_far = bw[n - 1] = arr[n - 1];
          
        for (int i = n - 2; i >= 0; i--) {
  
            cur_max = Math.max(arr[i], cur_max + arr[i]);
            max_so_far = Math.max(max_so_far, cur_max);
  
            // storing current maximum from ith, in
            // backward array
            bw[i] = cur_max;
        }
  
        /* Initializing final ans by max_so_far so that,
        case when no element is removed to get max sum
        subarray is also handled */
        int fans = max_so_far;
  
        // choosing maximum ignoring ith element
        for (int i = 1; i < n - 1; i++)
            fans = Math.max(fans, fw[i - 1] + bw[i + 1]);
  
        return fans;
    }
      
    // Driver code
    public static void main(String arg[])
    {
        int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
        int n = arr.length;
          
        System.out.print(maxSumSubarrayRemovingOneEle(
                                             arr, n));
    }
}
  
// This code is contributed by Anant Agarwal.

Python

# Python program to get maximum sum subarray removing
# at-most one element
  
# Method returns maximum sum of all subarray where
# removing one element is also allowed
def maxSumSubarrayRemovingOneEle(arr, n):
    # Maximum sum subarrays in forward and backward
    # directions
    fw = [0 for k in range(n)]
    bw = [0 for k in range(n)]
   
    # Initialize current max and max so far.
    cur_max, max_so_far = arr[0], arr[0]
   
    # calculating maximum sum subarrays in forward
    # direction
    for i in range(n):
        cur_max = max(arr[i], cur_max + arr[i])
        max_so_far = max(max_so_far, cur_max)
   
        # storing current maximum till ith, in
        # forward array
        fw[i] = cur_max
   
    # calculating maximum sum subarrays in backward
    # direction
    cur_max = max_so_far = bw[n-1] = arr[n-1]
    i = n-2
    while i >= 0:
        cur_max = max(arr[i], cur_max + arr[i])
        max_so_far = max(max_so_far, cur_max)
   
        # storing current maximum from ith, in
        # backward array
        bw[i] = cur_max
        i -= 1
   
    #  Initializing final ans by max_so_far so that,
    #  case when no element is removed to get max sum
    #  subarray is also handled
    fans = max_so_far
   
    #  choosing maximum ignoring ith element
    for i in range(1,n-1):
        fans = max(fans, fw[i - 1] + bw[i + 1])
   
    return fans
   
#  Driver code to test above methods
arr = [-2, -3, 4, -1, -2, 1, 5, -3]
n = len(arr)
print  maxSumSubarrayRemovingOneEle(arr, n)
  
# Contributed by: Afzal_Saan

C#

// C# program to get maximum sum subarray 
// removing at-most one element
using System;
class GFG {
      
    // Method returns maximum sum of all subarray where
    // removing one element is also allowed
    static int maxSumSubarrayRemovingOneEle(int []arr, 
                                                int n)
    {
          
        // Maximum sum subarrays in forward and 
        // backward directions
        int []fw = new int[n];
        int []bw = new int[n];
  
        // Initialize current max and max so far.
        int cur_max = arr[0], max_so_far = arr[0];
  
        // calculating maximum sum subarrays in forward
        // direction
        fw[0] = arr[0];
  
        for (int i = 1; i < n; i++) {
  
            cur_max = Math.Max(arr[i], cur_max + arr[i]);
            max_so_far = Math.Max(max_so_far, cur_max);
  
            // storing current maximum till ith, in
            // forward array
            fw[i] = cur_max;
        }
  
        // calculating maximum sum subarrays in backward
        // direction
        cur_max = max_so_far = bw[n - 1] = arr[n - 1];
          
        for (int i = n - 2; i >= 0; i--) {
  
            cur_max = Math.Max(arr[i], cur_max + arr[i]);
            max_so_far = Math.Max(max_so_far, cur_max);
  
            // storing current maximum from ith, in
            // backward array
            bw[i] = cur_max;
        }
  
        /* Initializing final ans by max_so_far so that,
        case when no element is removed to get max sum
        subarray is also handled */
        int fans = max_so_far;
  
        // choosing maximum ignoring ith element
        for (int i = 1; i < n - 1; i++)
            fans = Math.Max(fans, fw[i - 1] + bw[i + 1]);
  
        return fans;
    }
      
    // Driver code
    public static void Main()
    {
        int []arr = { -2, -3, 4, -1, -2, 1, 5, -3 };
        int n = arr.Length;
          
        Console.WriteLine(maxSumSubarrayRemovingOneEle(
                                            arr, n));
    }
}
  
// This code is contributed by anuj_67.

PHP

<?php
// PHP program to get maximum 
// sum subarray removing
// at-most one element
  
// Method returns maximum sum 
// of all subarray where removing 
// one element is also allowed
function maxSumSubarrayRemovingOneEle( $arr, $n)
{
    // Maximum sum subarrays in 
    // forward and backward directions
    $fw = array(); $bw = array();
  
    // Initialize current 
    // max and max so far.
    $cur_max = $arr[0]; 
    $max_so_far = $arr[0];
  
    // calculating maximum sum 
    // subarrays in forward direction
    $fw[0] = $arr[0];
    for ($i = 1; $i < $n; $i++)
    {
        $cur_max = max($arr[$i], 
                       $cur_max + $arr[$i]);
        $max_so_far = max($max_so_far
                          $cur_max);
  
        // storing current maximum till 
        // ith, in forward array
        $fw[$i] = $cur_max;
    }
  
    // calculating maximum sum 
    // subarrays in backward direction
    $cur_max = $max_so_far
    $bw[$n - 1] = $arr[$n - 1];
    for ( $i = $n - 2; $i >= 0; $i--)
    {
        $cur_max = max($arr[$i], 
                       $cur_max + $arr[$i]);
        $max_so_far = max($max_so_far
                          $cur_max);
  
        // storing current maximum from 
        // ith, in backward array
        $bw[$i] = $cur_max;
    }
  
    /* Initializing final ans by 
        max_so_far so that, case 
        when no element is removed 
        to get max sum subarray is 
        also handled */
    $fans = $max_so_far;
  
    // choosing maximum 
    // ignoring ith element
    for ($i = 1; $i < $n - 1; $i++)
        $fans = max($fans, $fw[$i - 1] + 
                           $bw[$i + 1]);
  
    return $fans;
}
  
// Driver Code
$arr = array(-2, -3, 4, -1, 
             -2, 1, 5, -3);
$n = count($arr);
echo maxSumSubarrayRemovingOneEle($arr, $n);
  
// This code is contributed by anuj_67.
?>


Output :

9

Time Complexity : O(n)
Auxiliary Space : O(n)

This article is contributed by Utkarsh Trivedi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Improved By : vt_m

Article Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.