Maximum Subarray Sum Excluding Certain Elements | Java Program implementation of the above idea ; Function to calculate the max sum of contigous subarray of B whose elements are not present in A ; mark all the elements present in B ; initialize max_so_far with INT_MIN ; traverse the array A ; if current max is greater than max so far then update max so far ; Driver code ; Function call
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 ) ) ; } }