# Maximum sum subarray removing at most one element in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array. Our task is to create a program that will find maximum sum subarray removing at most one element in c++.

Basically, we need to find one element which when removed provides the maximum sum for the elements remaining in the array.

Let’s take an example to understand the problem,

Input − array = {5, 1, 9, 2, -1, 7}

Output − 24

Explanation − we have removed -1 from the array and the sum became the maximum of all possible outcomes.

One solution to this problem will be finding the minimum element of the array and then finding the sum of all remaining elements of the array.

But here, element removal condition is not applied, kadane’s algorithm will solve the problem in a better way. So, here we will calculate the max sum in such a way that we will find sum till ith element from start and from end too.

And then check which ith element when skipped using the start and end sum arrays and then print the sum after skipping the given element.

## Example

Program to show the implementation of our solution,

Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxSubarraySum(int array[], int n){
int startSum[n], endSum[n];
int maxSum = array[0], overAllMax = array[0];
startSum[0] = array[0];
for (int i = 1; i < n; i++){
maxSum = max(array[i], maxSum + array[i]);
overAllMax = max(overAllMax, maxSum);
startSum[i] = maxSum;
}
maxSum = endSum[n-1] = array[n-1];
for (int i = n-2; i >= 0; i--){
maxSum = max(array[i], maxSum + array[i]);
overAllMax = max(overAllMax, maxSum);
endSum[i] = maxSum;
}
int SubArraySum = overAllMax;
for (int i = 1; i < n - 1; i++)
SubArraySum = max(SubArraySum, startSum[i - 1] + endSum[i + 1]);
return SubArraySum;
}
int main()
{
int array[] = {5, 7, 1, -1, 4, 2, 9};
int n = sizeof(array) / sizeof(array[0]);
cout<;"The maximum subarray after removing one element is "<<maxSubarraySum(array, n);
return 0;
}

## Output

The maximum subarray after removing one element is 28
Published on 30-Jan-2020 12:53:43