# Maximum Subarray Sum Excluding Certain Elements

Given an array of A of n integers and an array B of m integers find the Maximum Contiguous Subarray Sum of array A such that any element of array B is not present in that subarray

Examples :

Input : A = {1, 7, -10, 6, 2}, B = {5, 6, 7, 1}
Output : 2
Explanation Since the Maximum Sum Subarray of A is not allowed to have any element that is present in array B.
The Maximum Sum Subarray satisfying this is {2} as the only allowed subarrays are:{-10} and {2}. The Maximum Sum Subarray being {2} which sums to 2

Input : A = {3, 4, 5, -4, 6}, B = {1, 8, 5}
Output : 7

Explanation
The Maximum Sum Subarray satisfying this is {3, 4} as the only allowed subarrays are {3}, {4}, {3, 4}, {-4}, {6}, {-4, 6}. The Maximum Sum subarray being {3, 4} which sums to 7

Method 1 (O(n*m) approach):
We can solve this problem using the Kadane’s Algorithm. Since we don’t want any of the elements of array B to be part of any subarray of A, we need to modify the classical Kadane’s Algorithm a little.

Whenever we consider an element in the Kadane’s algorithm we either extend current subarray or we start a new subarray.

```curr_max = max(a[i], curr_max+a[i]);
if (curr_max < 0)
curr_max = 0
```

Now, in this problem when we consider any element, we check by linearly searching in the array B, if that element is present in B then we set curr_max to zero which means that at that index all subarrays we considered upto that point would end and not be extended further as no further contiguous arrays can be formed, i.e

If Ai is present in B, all subarrays in A from 0 to (i – 1) cannot be extended further as, the ith element can never be included in any subarray

If the current element of array A is not part of array B, we proceed with the Kadane’s Algorithm and keep track of the max_so_far.

## C++

 `// C++ Program to find max subarray ` `// sum excluding some elements ` `#include ` `using` `namespace` `std; ` ` `  `// Function to check the element  ` `// present in array B ` `bool` `isPresent(``int` `B[], ``int` `m, ``int` `x) ` `{ ` `    ``for` `(``int` `i = 0; i < m; i++) ` `        ``if` `(B[i] == x) ` `            ``return` `true``; ` `    ``return` `false``; ` `} ` ` `  `// Utility function for findMaxSubarraySum() ` `// with the following parameters  ` `// A => Array A, ` `// B => Array B, ` `// n => Number of elements in Array A, ` `// m => Number of elements in Array B  ` `int` `findMaxSubarraySumUtil(``int` `A[], ``int` `B[], ` `                        ``int` `n, ``int` `m) ` `{ ` ` `  `    ``// set max_so_far to INT_MIN ` `    ``int` `max_so_far = INT_MIN, curr_max = 0; ` ` `  `    ``for` `(``int` `i = 0; i < n; i++) { ` ` `  `        ``// if the element is present in B,  ` `        ``// set current max to 0 and move to  ` `        ``// the next element */ ` `        ``if` `(isPresent(B, m, A[i])) { ` `            ``curr_max = 0; ` `            ``continue``; ` `        ``} ` ` `  `        ``// Proceed as in Kadane's Algorithm  ` `        ``curr_max = max(A[i], curr_max + A[i]); ` `        ``max_so_far = max(max_so_far, curr_max); ` `    ``} ` `    ``return` `max_so_far; ` `} ` ` `  `// Wrapper for findMaxSubarraySumUtil()  ` `void` `findMaxSubarraySum(``int` `A[], ``int` `B[], ` `                        ``int` `n, ``int` `m) ` `{ ` `    ``int` `maxSubarraySum = findMaxSubarraySumUtil(A, B, ` `                                                ``n, m); ` ` `  `    ``// This case will occour when all elements ` `    ``// of A are present in B, thus ` `    ``// no subarray can be formed  ` `    ``if` `(maxSubarraySum == INT_MIN) { ` `        ``cout << ``"Maximum Subarray Sum cant be found"` `             ``<< endl; ` `    ``} ` `    ``else` `{ ` `        ``cout << ``"The Maximum Subarray Sum = "` `            ``<< maxSubarraySum << endl; ` `    ``} ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `A[] = { 3, 4, 5, -4, 6 }; ` `    ``int` `B[] = { 1, 8, 5 }; ` ` `  `    ``int` `n = ``sizeof``(A) / ``sizeof``(A); ` `    ``int` `m = ``sizeof``(B) / ``sizeof``(B); ` ` `  `    ``// Calling function ` `    ``findMaxSubarraySum(A, B, n, m); ` ` `  `    ``return` `0; ` `} `

## Java

 `// Java Program to find max subarray ` `// sum excluding some elements ` `import` `java.io.*; ` ` `  `class` `GFG { ` ` `  `    ``// Function to check the element  ` `    ``// present in array B ` `    ``static` `boolean` `isPresent(``int` `B[], ` `                            ``int` `m, ` `                            ``int` `x) ` `    ``{ ` `        ``for` `(``int` `i = ``0``; i < m; i++) ` `            ``if` `(B[i] == x) ` `                ``return` `true``; ` ` `  `        ``return` `false``; ` `    ``} ` ` `  `    ``// Utility function for findMaxSubarraySum() ` `    ``// with the following parameters ` `    ``// A => Array A, ` `    ``// B => Array B, ` `    ``// n => Number of elements in Array A, ` `    ``// m => Number of elements in Array B ` `    ``static` `int` `findMaxSubarraySumUtil(``int` `A[], ``int` `B[], ` `                                      ``int` `n, ``int` `m) ` `    ``{ ` ` `  `        ``// set max_so_far to INT_MIN ` `        ``int` `max_so_far = -``2147483648``, curr_max = ``0``; ` ` `  `        ``for` `(``int` `i = ``0``; i < n; i++) { ` ` `  `            ``// if the element is present in B, ` `            ``// set current max to 0 and move to ` `            ``// the next element ` `            ``if` `(isPresent(B, m, A[i])) { ` `                ``curr_max = ``0``; ` `                ``continue``; ` `            ``} ` ` `  `            ``// Proceed as in Kadane's Algorithm ` `            ``curr_max = Math.max(A[i], curr_max + A[i]); ` `            ``max_so_far = Math.max(max_so_far, curr_max); ` `        ``} ` `        ``return` `max_so_far; ` `    ``} ` ` `  `    ``// Wrapper for findMaxSubarraySumUtil() ` `    ``static` `void` `findMaxSubarraySum(``int` `A[], ``int` `B[], ` `                                   ``int` `n, ``int` `m) ` `    ``{ ` `        ``int` `maxSubarraySum = findMaxSubarraySumUtil(A, B, ` `                                                    ``n, m); ` ` `  `        ``// This case will occour when all ` `        ``// elements of A are present ` `        ``// in B, thus no subarray can be formed ` `        ``if` `(maxSubarraySum == -``2147483648``) { ` `                        ``System.out.println(``"Maximum Subarray Sum"` `                                        ``+ ``" "` `+ ``"can't be found"``); ` `                                             `  `        ``} ` `        ``else` `{ ` `            ``System.out.println(``"The Maximum Subarray Sum = "` `                                ``+ maxSubarraySum); ` `        ``} ` `    ``} ` ` `  `    ``// Driver code ` `    ``public` `static` `void` `main(String[] args) ` `    ``{ ` ` `  `        ``int` `A[] = { ``3``, ``4``, ``5``, -``4``, ``6` `}; ` `        ``int` `B[] = { ``1``, ``8``, ``5` `}; ` ` `  `        ``int` `n = A.length; ` `        ``int` `m = B.length; ` ` `  `        ``// Calling Function ` `        ``findMaxSubarraySum(A, B, n, m); ` `    ``} ` `} ` ` `  `// This code is contributed by Ajit. `

## Python3

 `# Python Program to find max  ` `# subarray sum excluding some ` `# elements  ` ` `  `# Function to check the element  ` `# present in array B  ` `INT_MIN ``=` `-``2147483648` ` `  `def` `isPresent(B, m, x): ` `    ``for` `i ``in` `range``(``0``, m): ` `        ``if` `B[i] ``=``=` `x: ` `            ``return` `True` `    ``return` `False` `     `  `# Utility function for findMaxSubarraySum()  ` `# with the following parameters  ` `# A => Array A,  ` `# B => Array B,  ` `# n => Number of elements in Array A,  ` `# m => Number of elements in Array B  ` `def` `findMaxSubarraySumUtil(A, B, n, m):  ` `     `  `    ``#set max_so_far to INT_MIN ` `    ``max_so_far ``=` `INT_MIN ` `    ``curr_max ``=` `0` `    ``for` `i ``in` `range``(``0``, n): ` `        ``if` `isPresent(B, m, A[i]) ``=``=` `True``: ` `            ``curr_max ``=` `0` `            ``continue` `             `  `        ``# Proceed as in Kadane's Algorithm ` `        ``curr_max ``=` `max``(A[i], curr_max ``+` `A[i]) ` `        ``max_so_far ``=` `max``(max_so_far, curr_max) ` `    ``return` `max_so_far ` ` `  `# Wrapper for findMaxSubarraySumUtil() ` `def` `findMaxSubarraySum(A, B, n, m): ` `     `  `    ``maxSubarraySum ``=` `findMaxSubarraySumUtil(A, B, n, m) ` `     `  `    ``# This case will occour when all   ` `    ``# elements of A are present  ` `    ``# in B, thus no subarray can be  ` `    ``# formed  ` `    ``if` `maxSubarraySum ``=``=` `INT_MIN: ` `        ``print``(``'Maximum Subarray Sum cant be found'``) ` `    ``else``: ` `        ``print``(``'The Maximum Subarray Sum ='``,  ` `                            ``maxSubarraySum) ` ` `  `# Driver code ` `A ``=` `[``3``, ``4``, ``5``, ``-``4``, ``6` `] ` `B ``=` `[ ``1``, ``8``, ``5` `] ` `n ``=` `len``(A) ` `m ``=` `len``(B) ` ` `  `# Calling function  ` `findMaxSubarraySum(A, B, n, m) ` ` `  `# This code is contributed ` `# by sahil shelangia `

## C#

 `// C# Program to find max subarray ` `// sum excluding some elements ` `using` `System; ` ` `  `class` `GFG { ` `     `  `    ``// Function to check the element  ` `    ``// present in array B ` `    ``static` `bool` `isPresent(``int``[] B, ``int` `m,  ` `                                   ``int` `x) ` `    ``{ ` `        ``for` `(``int` `i = 0; i < m; i++) ` `            ``if` `(B[i] == x) ` `                ``return` `true``; ` ` `  `        ``return` `false``; ` `    ``} ` ` `  `    ``// Utility function for findMaxSubarraySum() ` `    ``// with the following parameters ` `    ``// A => Array A, ` `    ``// B => Array B, ` `    ``// n => Number of elements in Array A, ` `    ``// m => Number of elements in Array B ` `    ``static` `int` `findMaxSubarraySumUtil(``int``[] A, ``int``[] B, ` `                                      ``int` `n, ``int` `m) ` `    ``{ ` ` `  `        ``// set max_so_far to INT_MIN ` `        ``int` `max_so_far = -2147483648, curr_max = 0; ` ` `  `        ``for` `(``int` `i = 0; i < n; i++) { ` ` `  `            ``// if the element is present in B, ` `            ``// set current max to 0 and move to ` `            ``// the next element ` `            ``if` `(isPresent(B, m, A[i])) { ` `                ``curr_max = 0; ` `                ``continue``; ` `            ``} ` ` `  `            ``// Proceed as in Kadane's Algorithm ` `            ``curr_max = Math.Max(A[i], curr_max + A[i]); ` `            ``max_so_far = Math.Max(max_so_far, curr_max); ` `        ``} ` `        ``return` `max_so_far; ` `    ``} ` ` `  `    ``// Wrapper for findMaxSubarraySumUtil() ` `    ``static` `void` `findMaxSubarraySum(``int``[] A, ``int``[] B, ` `                                    ``int` `n, ``int` `m) ` `    ``{ ` `        ``int` `maxSubarraySum = findMaxSubarraySumUtil(A, B, ` `                                                    ``n, m); ` ` `  `        ``// This case will occour when all ` `        ``// elements of A are present ` `        ``// in B, thus no subarray can be formed ` `        ``if` `(maxSubarraySum == -2147483648) ` `        ``{ ` `            ``Console.Write(``"Maximum Subarray Sum"` `                           ``+ ``" "` `+ ``"can't be found"``); ` `                                             `  `        ``} ` `        ``else`  `        ``{ ` `            ``Console.Write(``"The Maximum Subarray Sum = "` `                           ``+ maxSubarraySum); ` `        ``} ` `    ``} ` `     `  `    ``// Driver Code ` `    ``static` `public` `void` `Main () ` `    ``{ ` `         `  `        ``int``[] A = {3, 4, 5, -4, 6}; ` `        ``int``[] B = {1, 8, 5}; ` ` `  `        ``int` `n = A.Length; ` `        ``int` `m = B.Length; ` ` `  `        ``// Calling Function ` `        ``findMaxSubarraySum(A, B, n, m); ` `     `  `    ``} ` `} ` ` `  `// This code is contributed by Shrikant13. `

## PHP

 ` Array A, ` `// B => Array B, ` `// n => Number of elements ` `//      in Array A, ` `// m => Number of elements  ` `//      in Array B  ` `function` `findMaxSubarraySumUtil(``\$A``, ``\$B``, ` `                                ``\$n``, ``\$m``) ` `{ ` ` `  `    ``// set max_so_far ` `    ``// to INT_MIN ` `    ``\$max_so_far` `= PHP_INT_MIN; ` `    ``\$curr_max` `= 0; ` ` `  `    ``for` `(``\$i` `= 0; ``\$i` `< ``\$n``; ``\$i``++)  ` `    ``{ ` ` `  `        ``// if the element is present  ` `        ``// in B, set current max to  ` `        ``// 0 and move to the next  ` `        ``// element  ` `        ``if` `(isPresent(``\$B``, ``\$m``, ``\$A``[``\$i``])) ` `        ``{ ` `            ``\$curr_max` `= 0; ` `            ``continue``; ` `        ``} ` ` `  `        ``// Proceed as in ` `        ``// Kadane's Algorithm  ` `        ``\$curr_max` `= max(``\$A``[``\$i``],  ` `        ``\$curr_max` `+ ``\$A``[``\$i``]); ` `        ``\$max_so_far` `= max(``\$max_so_far``,  ` `                          ``\$curr_max``); ` `    ``} ` `    ``return` `\$max_so_far``; ` `} ` ` `  `// Wrapper for  ` `// findMaxSubarraySumUtil()  ` `function` `findMaxSubarraySum(``\$A``, ``\$B``, ` `                            ``\$n``, ``\$m``) ` `{ ` `    ``\$maxSubarraySum` `= findMaxSubarraySumUtil(``\$A``, ``\$B``, ` `                                             ``\$n``, ``\$m``); ` ` `  `    ``// This case will occour  ` `    ``// when all elements of  ` `    ``// A are present in ` `    ``// B, thus no subarray  ` `    ``// can be formed  ` `    ``if` `(``\$maxSubarraySum` `== PHP_INT_MIN)  ` `    ``{ ` `        ``echo` `(``"Maximum Subarray "` `.  ` `            ``"Sum cant be found\n"``); ` `    ``} ` `    ``else`  `    ``{ ` `        ``echo` `(``"The Maximum Subarray Sum = "``.  ` `                     ``\$maxSubarraySum``. ``"\n"``); ` `    ``} ` `} ` ` `  `// Driver Code ` `\$A` `= ``array``(3, 4, 5, -4, 6); ` `\$B` `= ``array``(1, 8, 5); ` ` `  `\$n` `= ``count``(``\$A``); ` `\$m` `= ``count``(``\$B``); ` ` `  `// Calling function ` `findMaxSubarraySum(``\$A``, ``\$B``, ``\$n``, ``\$m``); ` ` `  `// This code is contributed by  ` `// Manish Shaw(manishshaw1) ` `?> `

Output :

```The Maximum Subarray Sum = 7
```

Time Complexity of this approach is O(n*m)

Method 2 (O((n+m)*log(m)) approach)
The main idea behind this approach is exactly the same as that of method 1. This approach just makes the searching of an element of array A, in array B, faster by using Binary Search
Note: We need to sort the Array B to apply Binary Search on it.

## C++

 `// C++ Program to find max subarray  ` `// sum excluding some elements ` `#include ` `using` `namespace` `std; ` ` `  `// Utility function for findMaxSubarraySum() ` `// with the following parameters  ` `// A => Array A, ` `// B => Array B, ` `// n => Number of elements in Array A, ` `// m => Number of elements in Array B  ` `int` `findMaxSubarraySumUtil(``int` `A[], ``int` `B[], ` `                           ``int` `n, ``int` `m) ` `{ ` ` `  `    ``// set max_so_far to INT_MIN ` `    ``int` `max_so_far = INT_MIN, curr_max = 0; ` ` `  `    ``for` `(``int` `i = 0; i < n; i++) { ` ` `  `        ``// if the element is present in B,  ` `        ``// set current max to 0 and move to ` `        ``// the next element  ` `        ``if` `(binary_search(B, B + m, A[i])) { ` `            ``curr_max = 0; ` `            ``continue``; ` `        ``} ` ` `  `        ``// Proceed as in Kadane's Algorithm  ` `        ``curr_max = max(A[i], curr_max + A[i]); ` `        ``max_so_far = max(max_so_far, curr_max); ` `    ``} ` `    ``return` `max_so_far; ` `} ` ` `  `// Wrapper for findMaxSubarraySumUtil() ` `void` `findMaxSubarraySum(``int` `A[], ``int` `B[],  ` `                        ``int` `n, ``int` `m) ` `{ ` `    ``// sort array B to apply Binary Search ` `    ``sort(B, B + m); ` ` `  `    ``int` `maxSubarraySum = findMaxSubarraySumUtil(A, B,  ` `                                                ``n, m); ` ` `  `    ``// This case will occour when all elements ` `    ``// of A are present in B, thus no subarray  ` `    ``// can be formed  ` `    ``if` `(maxSubarraySum == INT_MIN) { ` `        ``cout << ``"Maximum subarray sum cant be found"` `            ``<< endl; ` `    ``} ` `    ``else` `{ ` `        ``cout << ``"The Maximum subarray sum = "` `             ``<< maxSubarraySum << endl; ` `    ``} ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``int` `A[] = { 3, 4, 5, -4, 6 }; ` `    ``int` `B[] = { 1, 8, 5 }; ` ` `  `    ``int` `n = ``sizeof``(A) / ``sizeof``(A); ` `    ``int` `m = ``sizeof``(B) / ``sizeof``(B); ` ` `  `    ``// Calling fucntion ` `    ``findMaxSubarraySum(A, B, n, m); ` `    ``return` `0; ` `} `

## Java

 `// Java Program to find max subarray  ` `// sum excluding some elements ` `import` `java.util.*; ` ` `  `class` `GFG  ` `{ ` ` `  `    ``// Utility function for findMaxSubarraySum() ` `    ``// with the following parameters  ` `    ``// A => Array A, ` `    ``// B => Array B, ` `    ``// n => Number of elements in Array A, ` `    ``// m => Number of elements in Array B  ` `    ``static` `int` `findMaxSubarraySumUtil(``int` `A[], ``int` `B[], ` `                                        ``int` `n, ``int` `m)  ` `    ``{ ` ` `  `        ``// set max_so_far to INT_MIN ` `        ``int` `max_so_far = Integer.MIN_VALUE, curr_max = ``0``; ` ` `  `        ``for` `(``int` `i = ``0``; i < n; i++)  ` `        ``{ ` ` `  `            ``// if the element is present in B,  ` `            ``// set current max to 0 and move to ` `            ``// the next element  ` `            ``if` `(Arrays.binarySearch(B, A[i]) >= ``0``)  ` `            ``{ ` `                ``curr_max = ``0``; ` `                ``continue``; ` `            ``} ` ` `  `            ``// Proceed as in Kadane's Algorithm  ` `            ``curr_max = Math.max(A[i], curr_max + A[i]); ` `            ``max_so_far = Math.max(max_so_far, curr_max); ` `        ``} ` `        ``return` `max_so_far; ` `    ``} ` ` `  `    ``// Wrapper for findMaxSubarraySumUtil() ` `    ``static` `void` `findMaxSubarraySum(``int` `A[], ``int` `B[], ` `                                        ``int` `n, ``int` `m)  ` `    ``{ ` `        ``// sort array B to apply Binary Search ` `        ``Arrays.sort(B); ` ` `  `        ``int` `maxSubarraySum = findMaxSubarraySumUtil(A, B, ` `                ``n, m); ` ` `  `        ``// This case will occour when all elements ` `        ``// of A are present in B, thus no subarray  ` `        ``// can be formed  ` `        ``if` `(maxSubarraySum == Integer.MIN_VALUE)  ` `        ``{ ` `            ``System.out.println(``"Maximum subarray sum cant be found"``); ` `        ``}  ` `        ``else`  `        ``{ ` `            ``System.out.println(``"The Maximum subarray sum = "` `                    ``+ maxSubarraySum); ` `        ``} ` `    ``} ` ` `  `    ``// Driver Code ` `    ``public` `static` `void` `main(String[] args)  ` `    ``{ ` `        ``int` `A[] = {``3``, ``4``, ``5``, -``4``, ``6``}; ` `        ``int` `B[] = {``1``, ``8``, ``5``}; ` ` `  `        ``int` `n = A.length; ` `        ``int` `m = B.length; ` ` `  `        ``// Calling fucntion ` `        ``findMaxSubarraySum(A, B, n, m); ` `    ``} ` `} ` ` `  `// This code has been contributed by 29AjayKumar `

Output :

```The Maximum subarray sum = 7
```

Time Complexity of this approach is O(nlog(m) + mlog(m)) or O((n + m)log(m)).
Note: The mlog(m) factor is due to sorting the array B.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.