Maximize the maximum subarray sum after removing at most one element in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array arr[] of N integers. The task is to first find the maximum sub-array sum and then remove at most one element from the sub-array. Remove at most a single element such that the maximum sum after removal is maximized.

If given input array is {1, 2, 3, -2, 3} then maximum sub-array sum is {2, 3, -2, 3}. Then we can remove -2. After removing the remaining array becomes−

{1, 2, 3, 3} with sum 9 which is maximum.

Algorithm

1. Use Kadane’s algorithm to find the maximum subarray sum.
2. Once the sum has beens find, re-apply Kadane’s algorithm to find the maximum sum again with some minor changes)

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxSubarraySum(int *arr, int n){
   int max = INT_MIN;
   int currentMax = 0;
   for (int i = 0; i < n; ++i) {
      currentMax = currentMax + arr[i];
      if (max < currentMax) {
         max = currentMax;
      }
      if (currentMax < 0) {
         currentMax = 0;
      }
   }
   return max;
}
int getMaxSum(int *arr, int n){
   int cnt = 0;
   int minVal = INT_MAX;
   int minSubarr = INT_MAX;
   int sum = getMaxSubarraySum(arr, n);
   int max = INT_MIN;
   int currentMax = 0;
   for (int i = 0; i < n; ++i) {
      currentMax = currentMax + arr[i];
      ++cnt;
      minSubarr = min(arr[i], minSubarr);
      if (sum == currentMax) {
         if (cnt == 1) {
            minVal = min(minVal, 0);
         } else {
            minVal = min(minVal, minSubarr);
         }
      }
      if (currentMax < 0) {
         currentMax = 0;
         cnt = 0;
         minSubarr = INT_MAX;
      }
   }
   return sum - minVal;
}
int main(){
   int arr[] = {1, 2, 3, -2, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Maximum sum = " << getMaxSum(arr, n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output−

Maximum sum = 9
raja
Published on 24-Dec-2019 07:01:43
Advertisements