Computer >> Computer tutorials >  >> Programming >> C++

Maximum Subarray Sum Excluding Certain Elements in C++


In this tutorial, we will be discussing a program to find maximum Subarray Sum Excluding Certain Elements.

For this we will be provided with two arrays of size M and N. Our task is to find a sub-array in the first array such that no element inside the subarray is present inside the second array and the elements of subarray sum up to be maximum.

Example

#include <bits/stdc++.h>
using namespace std;
//checking if element is present in second array
bool isPresent(int B[], int m, int x) {
   for (int i = 0; i < m; i++)
   if (B[i] == x)
   return true;
   return false;
}
int findMaxSubarraySumUtil(int A[], int B[], int n, int m) {
   int max_so_far = INT_MIN, curr_max = 0;
   for (int i = 0; i < n; i++) {
      if (isPresent(B, m, A[i])) {
         curr_max = 0;
         continue;
      }
      curr_max = max(A[i], curr_max + A[i]);
      max_so_far = max(max_so_far, curr_max);
   }
   return max_so_far;
}
void findMaxSubarraySum(int A[], int B[], int n, int m) {
   int maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m);
   if (maxSubarraySum == INT_MIN) {
      cout << "Maximum Subarray Sum cant be found" << endl;
   } else {
      cout << "The Maximum Subarray Sum = " << maxSubarraySum << endl;
   }
}
int main() {
   int A[] = { 3, 4, 5, -4, 6 };
   int B[] = { 1, 8, 5 };
   int n = sizeof(A) / sizeof(A[0]);
   int m = sizeof(B) / sizeof(B[0]);
   findMaxSubarraySum(A, B, n, m);
   return 0;
}

Output

The Maximum Subarray Sum = 7