# Maximum Subarray Sum with One Deletion in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have an array of integers; we have to find the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, we can say that we want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. We have to keep in mind that the subarray needs to be non-empty after deleting one element. So if the input is like [1,-2,0,3], then the output will be 4. So if we delete -2, it will return the max sum.

To solve this, we will follow these steps −

• n := size of array, and := a[0]
• suff_with_del := 0, suff_with_out_del := a[0]
• for i in range i to n – 1
• suff_with_del := max of suff_with_del + a[i] and suff_with_out_del
• suff_with_out_del := max of a[i] and suff_with_out_del + a[i]
• ans := max of ans, suff_with_out_del and suff_with _del
• return res

## Example(C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maximumSum(vector<int>& a) {
int n = a.size();
int ans = a[0];
int suffix_with_deletion = 0;
int suffix_with_not_deletion = a[0];
for(int i = 1;i<n;i++){
suffix_with_deletion = max(suffix_with_deletion + a[i], suffix_with_not_deletion);
suffix_with_not_deletion = max(a[i],suffix_with_not_deletion+a[i]);
ans = max({ans, suffix_with_not_deletion,suffix_with_deletion});
}
return ans;
}
};
main(){
vector<int> v = {1,-2,0,3};
Solution ob;
cout <<ob.maximumSum(v);
}

## Input

[1,-2,0,3]

## Output

4
Updated on 30-Apr-2020 06:36:31