- Related Questions & Answers
- The Maximum Data Rate of a Channel
- C/C++ Program for Largest Sum Contiguous Subarray?
- C/C++ Program for Maximum height when coins are arranged in a triangle?
- Get the maximum count of distinct values in a separate column with MySQL
- How to get the data associated with the maximum id in a MySQL table?
- Getting the maximum value from a varchar field in MySQL
- Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL?
- Limiting numbers to a maximum value in MySQL?
- How to find maximum value in an array using spread operator in JavaScript?
- C++ Program to Find the maximum subarray sum using Binary Search approach
- Get maximum and minimum value in MongoDB?
- How to change the maximum value of a JSlider in Java?
- How to find the maximum value of an array in JavaScript?
- What is the MongoDB Capped Collection maximum allowable size?
- How to select the maximum value of a column in MySQL?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Let us see the following implementation to get better understanding −

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; } };

[1,-2,0,3]

4

Advertisements