Maximum Subarray Sum Excluding Certain Elements
Last Updated :
09 Aug, 2022
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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
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;
}
|
Java
import java.io.*;
class GFG {
static boolean isPresent( int B[], int m, int x)
{
for ( int i = 0 ; i < m; i++)
if (B[i] == x)
return true ;
return false ;
}
static int findMaxSubarraySumUtil( int A[], int B[],
int n, int m)
{
int max_so_far = - 2147483648 , curr_max = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (isPresent(B, m, A[i]))
{
curr_max = 0 ;
continue ;
}
curr_max = Math.max(A[i], curr_max + A[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
static void findMaxSubarraySum( int A[], int B[], int n,
int m)
{
int maxSubarraySum
= findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == - 2147483648 )
{
System.out.println( "Maximum Subarray Sum"
+ " "
+ "can't be found" );
}
else {
System.out.println( "The Maximum Subarray Sum = "
+ maxSubarraySum);
}
}
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;
findMaxSubarraySum(A, B, n, m);
}
}
|
Python3
INT_MIN = - 2147483648
def isPresent(B, m, x):
for i in range ( 0 , m):
if B[i] = = x:
return True
return False
def findMaxSubarraySumUtil(A, B, n, m):
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
curr_max = max (A[i], curr_max + A[i])
max_so_far = max (max_so_far, curr_max)
return max_so_far
def findMaxSubarraySum(A, B, n, m):
maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m)
if maxSubarraySum = = INT_MIN:
print ( 'Maximum Subarray Sum cant be found' )
else :
print ( 'The Maximum Subarray Sum =' ,
maxSubarraySum)
A = [ 3 , 4 , 5 , - 4 , 6 ]
B = [ 1 , 8 , 5 ]
n = len (A)
m = len (B)
findMaxSubarraySum(A, B, n, m)
|
C#
using System;
class GFG {
static bool isPresent( int [] B, int m, int x)
{
for ( int i = 0; i < m; i++)
if (B[i] == x)
return true ;
return false ;
}
static int findMaxSubarraySumUtil( int [] A, int [] B,
int n, int m)
{
int max_so_far = -2147483648, curr_max = 0;
for ( int i = 0; i < n; i++)
{
if (isPresent(B, m, A[i]))
{
curr_max = 0;
continue ;
}
curr_max = Math.Max(A[i], curr_max + A[i]);
max_so_far = Math.Max(max_so_far, curr_max);
}
return max_so_far;
}
static void findMaxSubarraySum( int [] A, int [] B, int n,
int m)
{
int maxSubarraySum
= findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == -2147483648)
{
Console.Write( "Maximum Subarray Sum"
+ " "
+ "can't be found" );
}
else {
Console.Write( "The Maximum Subarray Sum = "
+ maxSubarraySum);
}
}
static public void Main()
{
int [] A = { 3, 4, 5, -4, 6 };
int [] B = { 1, 8, 5 };
int n = A.Length;
int m = B.Length;
findMaxSubarraySum(A, B, n, m);
}
}
|
PHP
<?php
function isPresent( $B , $m , $x )
{
for ( $i = 0; $i < $m ; $i ++)
if ( $B [ $i ] == $x )
return true;
return false;
}
function findMaxSubarraySumUtil( $A , $B ,
$n , $m )
{
$max_so_far = PHP_INT_MIN;
$curr_max = 0;
for ( $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 ;
}
function findMaxSubarraySum( $A , $B ,
$n , $m )
{
$maxSubarraySum = findMaxSubarraySumUtil( $A , $B ,
$n , $m );
if ( $maxSubarraySum == PHP_INT_MIN)
{
echo ( "Maximum Subarray " .
"Sum cant be found\n" );
}
else
{
echo ( "The Maximum Subarray Sum = " .
$maxSubarraySum . "\n" );
}
}
$A = array (3, 4, 5, -4, 6);
$B = array (1, 8, 5);
$n = count ( $A );
$m = count ( $B );
findMaxSubarraySum( $A , $B , $n , $m );
?>
|
Javascript
<script>
function isPresent(B, m, x)
{
for (let i = 0; i < m; i++)
if (B[i] == x)
return true ;
return false ;
}
function findMaxSubarraySumUtil(A, B,n, m)
{
let max_so_far = -2147483648, curr_max = 0;
for (let i = 0; i < n; i++)
{
if (isPresent(B, m, A[i]))
{
curr_max = 0;
continue ;
}
curr_max = Math.max(A[i], curr_max + A[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
function findMaxSubarraySum(A, B, n,
m)
{
let maxSubarraySum
= findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == -2147483648)
{
document.write( "Maximum Subarray Sum"
+ " "
+ "can't be found" );
}
else {
document.write( "The Maximum Subarray Sum = "
+ maxSubarraySum);
}
}
let A = [ 3, 4, 5, -4, 6 ];
let B = [ 1, 8, 5 ];
let n = A.length;
let m = B.length;
findMaxSubarraySum(A, B, n, m);
</script>
|
Output
The Maximum Subarray Sum = 7
Time Complexity: O(n*m)
Auxiliary Space: O(1)
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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
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 (binary_search(B, 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)
{
sort(B, B + 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;
}
|
Java
import java.util.*;
class GFG {
static int findMaxSubarraySumUtil( int A[], int B[],
int n, int m)
{
int max_so_far = Integer.MIN_VALUE, curr_max = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (Arrays.binarySearch(B, A[i]) >= 0 )
{
curr_max = 0 ;
continue ;
}
curr_max = Math.max(A[i], curr_max + A[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
static void findMaxSubarraySum( int A[], int B[], int n,
int m)
{
Arrays.sort(B);
int maxSubarraySum
= findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == Integer.MIN_VALUE)
{
System.out.println(
"Maximum subarray sum cant be found" );
}
else
{
System.out.println( "The Maximum subarray sum = "
+ maxSubarraySum);
}
}
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;
findMaxSubarraySum(A, B, n, m);
}
}
|
Python3
import sys
def binary_search(B, m, target):
start,end = 0 ,m - 1
while (start < = end):
mid = (start + end) / / 2
if (B[mid] = = target):
return True
elif (B[mid] < target):
start = mid + 1
else :
end = mid - 1
return False
def findMaxSubarraySumUtil(A, B, n, m):
max_so_far,curr_max = - sys.maxsize - 1 , 0
for i in range (n):
if (binary_search(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
def findMaxSubarraySum(A,B,n,m):
B.sort()
maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m)
if (maxSubarraySum = = - sys.maxsize - 1 ):
print ( "Maximum subarray sum cant be found" )
else :
print (f "The Maximum subarray sum = {maxSubarraySum}" )
A = [ 3 , 4 , 5 , - 4 , 6 ]
B = [ 1 , 8 , 5 ]
n = len (A)
m = len (B)
findMaxSubarraySum(A, B, n, m)
|
C#
using System;
class GFG {
static int findMaxSubarraySumUtil( int []A, int []B,
int n, int m)
{
int max_so_far = int .MinValue, curr_max = 0;
for ( int i = 0; i < n; i++)
{
if (Array.BinarySearch(B, A[i]) >= 0)
{
curr_max = 0;
continue ;
}
curr_max = Math.Max(A[i], curr_max + A[i]);
max_so_far = Math.Max(max_so_far, curr_max);
}
return max_so_far;
}
static void findMaxSubarraySum( int []A, int []B, int n,
int m)
{
Array.Sort(B);
int maxSubarraySum
= findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == int .MinValue)
{
Console.WriteLine(
"Maximum subarray sum cant be found" );
}
else
{
Console.WriteLine( "The Maximum subarray sum = "
+ maxSubarraySum);
}
}
public static void Main( params string [] args)
{
int []A = { 3, 4, 5, -4, 6 };
int []B = { 1, 8, 5 };
int n = A.Length;
int m = B.Length;
findMaxSubarraySum(A, B, n, m);
}
}
|
Javascript
<script>
function binary_search(B, m, target)
{
let start = 0, end = m - 1;
while (start <= end)
{
let mid = Math.floor((start + end)/2);
if (B[mid] === target) return true ;
else if (B[mid] < target)
start = mid + 1;
else
end = mid - 1;
}
return false ;
}
function findMaxSubarraySumUtil(A, B, n, m)
{
let max_so_far = Number.MIN_VALUE, curr_max = 0;
for (let i = 0; i < n; i++) {
if (binary_search(B, m, A[i])) {
curr_max = 0;
continue ;
}
curr_max = Math.max(A[i], curr_max + A[i]);
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
function findMaxSubarraySum(A,B,n,m)
{
B.sort();
let maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m);
if (maxSubarraySum == Number.MIN_VALUE) {
document.write( "Maximum subarray sum cant be found" , "</br>" );
}
else {
document.write(`The Maximum subarray sum = ${maxSubarraySum}`, "</br>" );
}
}
let A = [ 3, 4, 5, -4, 6 ];
let B = [ 1, 8, 5 ];
let n = A.length;
let m = B.length;
findMaxSubarraySum(A, B, n, m);
</script>
|
Output
The Maximum subarray sum = 7
Time Complexity: O(nlog(m) + mlog(m)) or O((n + m)log(m)).
Note: The mlog(m) factor is due to sorting the array B.
Auxiliary Space: O(1)
Method 3: O(max(n,m)) approach)
The main idea behind this approach is save B array in a map which will help you to check if A[i] is present in B or not.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int findMaxSubarraySum(vector< int > A,vector< int > B)
{
unordered_map< int , int > m;
for ( int i=0;i<B.size();i++)
{
m[B[i]]=1;
}
int max_so_far=INT_MIN;
int currmax=0;
for ( int i=0;i<A.size();i++)
{
if (currmax<0 || m[A[i]]==1)
{
currmax=0;
continue ;
}
currmax=max(A[i],A[i]+currmax);
if (max_so_far<currmax)
{
max_so_far=currmax;
}
}
return max_so_far;
}
int main()
{
vector< int > a = { 3, 4, 5, -4, 6 };
vector< int > b = { 1, 8, 5 };
cout << findMaxSubarraySum(a,b);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findMaxSubarraySum( int A[], int B[])
{
HashMap<Integer, Integer> m = new HashMap<>();
for ( int i = 0 ; i < B.length; i++)
{
m.put(B[i], 1 );
}
int max_so_far = Integer.MIN_VALUE;
int currmax = 0 ;
for ( int i = 0 ; i < A.length; i++)
{
if (currmax < 0 || (m.containsKey(A[i]) && m.get(A[i]) == 1 ))
{
currmax = 0 ;
continue ;
}
currmax = Math.max(A[i], A[i] + currmax);
if (max_so_far < currmax)
{
max_so_far = currmax;
}
}
return max_so_far;
}
public static void main(String[] args)
{
int a[] = { 3 , 4 , 5 , - 4 , 6 };
int b[] = { 1 , 8 , 5 };
System.out.println(findMaxSubarraySum(a, b));
}
}
|
Python3
import sys
def findMaxSubarraySum(A, B):
m = dict ()
for i in range ( len (B)):
if B[i] not in m:
m[B[i]] = 0
m[B[i]] = 1
max_so_far = - sys.maxsize - 1
currmax = 0
for i in range ( len (A)):
if (currmax < 0 or (A[i] in m and m[A[i]] = = 1 )):
currmax = 0
continue
currmax = max (A[i], A[i] + currmax)
if (max_so_far<currmax):
max_so_far = currmax
return max_so_far
if __name__ = = '__main__' :
a = [ 3 , 4 , 5 , - 4 , 6 ]
b = [ 1 , 8 , 5 ]
print (findMaxSubarraySum(a, b))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int findMaxSubarraySum( int [] A, int [] B)
{
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < B.Length; i++)
{
m[B[i]] = 1;
}
int max_so_far = Int32.MinValue;
int currmax = 0;
for ( int i = 0; i < A.Length; i++)
{
if (currmax<0 || (m.ContainsKey(A[i]) && m[A[i]] == 1))
{
currmax = 0;
continue ;
}
currmax = Math.Max(A[i],A[i]+currmax);
if (max_so_far<currmax)
{
max_so_far = currmax;
}
}
return max_so_far;
}
static void Main() {
int [] a = { 3, 4, 5, -4, 6 };
int [] b = { 1, 8, 5 };
Console.WriteLine(findMaxSubarraySum(a,b));
}
}
|
Javascript
<script>
function findMaxSubarraySum(A, B){
let m = new Map()
for (let i=0;i<A.length;i++){
if (m.has(B[i]))
m.set(B[i],0)
m.set(B[i],1)
}
max_so_far = Number.MIN_VALUE
currmax = 0
for (let i=0;i<A.length;i++){
if (currmax < 0 || (m.has(A[i]) && m.get(A[i]) == 1)){
currmax = 0
continue
}
currmax = Math.max(A[i], A[i] + currmax)
if (max_so_far<currmax)
max_so_far = currmax
}
return max_so_far
}
let a = [ 3, 4, 5, -4, 6 ]
let b = [ 1, 8, 5 ]
document.write(findMaxSubarraySum(a, b), "</br>" )
</script>
|
Time Complexity: O(max(n,m))
Auxiliary Space: O(n)
Similar Reads
Subarray with largest sum after excluding its maximum element
Given an array arr[], the task is to find the starting and ending indices of the subarray with the largest sum after excluding its maximum element.Examples: Input: arr[] = {5, -2, 10, -1, 4} Output: 1 5 Explanation: Subarray[1:5] = {5, -2, 10, -1, 4} Sum of subarray excluding maximum element = 5 + (
9 min read
Maximum Subarray Sum after inverting at most two elements
Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th i
11 min read
Maximum Sum Alternating Subarray
Given an array arr[] of size N, the task is to find the maximum alternating sum of a subarray possible for a given array. Alternating Subarray Sum: Considering a subarray {arr[i], arr[j]}, alternating sum of the subarray is arr[i] - arr[i + 1] + arr[i + 2] - ........ (+ / -) arr[j]. Examples: Input:
6 min read
Longest subarray having maximum sum
Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
12 min read
Maximum sum of Subset having no consecutive elements
Given an array arr[] of size N, the task is to find the maximum possible sum of a subset of the array such that no two consecutive elements are part of the subset. Examples: Input: arr[]= {2, 3, 2, 3, 3, 4}Output: 9Explanation: The subset having all the 3s i.e. {3, 3, 3} have sum = 9.This is the max
9 min read
Maximum Subarray Sum in a given Range
Given an array of n numbers, the task is to answer the following queries: maximumSubarraySum(start, end) : Find the maximum subarray sum in the range from array index 'start' to 'end'. Also see : Range Query With Update Required Examples: Input : arr[] = {1, 3, -4, 5, -2} Query 1: start = 0, end = 4
15+ min read
Maximum circular subarray sum
Given a circular array arr[] of size n, find the maximum possible sum of a non-empty subarray. Examples: Input: arr[] = {8, -8, 9, -9, 10, -11, 12}Output: 22Explanation: Circular Subarray {12, 8, -8, 9, -9, 10} has the maximum sum, which is 22. Input: arr[] = {10, -3, -4, 7, 6, 5, -4, -1}Output: 23
15+ min read
Maximum subarray sum by flipping signs of at most K array elements
Given an array arr[] of N integers and an integer K, The task is to find the maximum sub-array sum by flipping signs of at most K array elements. Examples: Input: arr[] = {-6, 2, -1, -1000, 2}, k = 2 Output: 1009 We can flip the signs of -6 and -1000, to get maximum subarray sum as 1009 Input: arr[]
9 min read
Maximum Subarray sum of A[] by adding any element of B[] at any end
Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it: Choose either the leftmost or rightmost
15 min read
Maximum sum bitonic subarray
Given an array containing n numbers. The problem is to find the maximum sum bitonic subarray. A bitonic subarray is a subarray in which elements are first increasing and then decreasing. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray. Time Complexity of O
15+ min read