Maximize sum of subsets from two arrays having no consecutive values | Function to calculate maximum subset sum ; Initialize array to store dp states ; Base Cases ; Pre initializing for dp [ 0 ] & dp [ 1 ] ; Calculating dp [ index ] based on above formula ; Prlet maximum subset sum ; Given arrays ; Length of the array
function maximumSubsetSum ( arr1 , arr2 , length ) { let dp = new Array ( length ) . fill ( 0 ) ; ; if ( length == 1 ) { document . write ( Math . max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ; return ; } if ( length == 2 ) { document . write ( Math . max ( Math . max ( arr1 [ 1 ] , arr2 [ 1 ] ) , Math . max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ) ; return ; } else { dp [ 0 ] = Math . max ( arr1 [ 0 ] , arr2 [ 0 ] ) ; dp [ 1 ] = Math . max ( Math . max ( arr1 [ 1 ] , arr2 [ 1 ] ) , Math . max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ; let index = 2 ; while ( index < length ) { dp [ index ] = Math . max ( Math . max ( arr1 [ index ] , arr2 [ index ] ) , Math . max ( Math . max ( arr1 [ index ] + dp [ index - 2 ] , arr2 [ index ] + dp [ index - 2 ] ) , dp [ index - 1 ] ) ) ; ++ index ; } document . write ( dp [ length - 1 ] ) ; } } let arr1 = [ - 1 , - 2 , 4 , - 4 , 5 ] ; let arr2 = [ - 1 , - 2 , - 3 , 4 , 10 ] ; let length = arr1 . length ; maximumSubsetSum ( arr1 , arr2 , length ) ;