Maximum sum subarray removing at most one element

06 Jul, 2022
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) 
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// 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 allowedint 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,max(0, fw[i - 1]) +max(0, bw[i + 1]));  // In this condition we are checking when removing the ith element  // so checking the max(0,left)+max(0,right), because maybe  // left<0 || right<0 so it wont contribute to the answer        if(fans==0){          // if no positive element in array so return max_element            return *max_element(arr,arr+n);        }    return fans; } // Driver code to test above methodsint 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 program to get maximum sum subarray// removing at-most one elementclass 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 program to get maximum sum subarray removing# at-most one element # Method returns maximum sum of all subarray where# removing one element is also alloweddef 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]    fw[0] = cur_max      # calculating maximum sum subarrays in forward    # direction    for i in range(1,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 methodsarr = [-2, -3, 4, -1, -2, 1, 5, -3]n = len(arr)print (maxSumSubarrayRemovingOneEle(arr, n)) # Contributed by: Afzal_Saan
// C# program to get maximum sum subarray// removing at-most one elementusing 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 program to get maximum// sum subarray removing// at-most one element // Method returns maximum sum// of all subarray where removing// one element is also allowedfunction 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.?>
<script> // JavaScript program to get maximum sum subarray// removing at-most one element  // Method returns maximum sum of all subarray where// removing one element is also allowedfunction maxSumSubarrayRemovingOneEle(arr, n){         // Maximum sum subarrays in forward and    // backward directions    let fw = [];    let bw = [];     // Initialize current max and max so far.    let cur_max = arr[0], max_so_far = arr[0];     // calculating maximum sum subarrays in forward    // direction    fw[0] = arr[0];     for(let 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(let 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 */    let fans = max_so_far;     // Choosing maximum ignoring ith element    for(let i = 1; i < n - 1; i++)        fans = Math.max(fans, fw[i - 1] +                              bw[i + 1]);     return fans;} // Driver Codelet arr = [ -2, -3, 4, -1, -2, 1, 5, -3 ];let n = arr.length;       document.write(    maxSumSubarrayRemovingOneEle(arr, n));   </script>
Output : 
9
Time Complexity : O(n) Auxiliary Space : O(n)
This article is contributed by Vinish Thanai If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
vt_m
rogerhong1996
code_hunt
drunkenstein
amartyaghoshgfg
hardikkoriintern
subarray
subarray-sum
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Find if there is a path between two vertices in an undirected graph
Subset Sum Problem | DP-25