Sum of subsets nearest to K possible from two given arrays | Stores the sum closest to K ; Stores the minimum absolute difference ; Function to choose the elements from the array B [ ] ; If absolute difference is less then minimum value ; Update the minimum value ; Update the value of ans ; If absolute difference between curr and K is equal to minimum ; Update the value of ans ; If i is greater than M - 1 ; Includes the element B [ i ] once ; Includes the element B [ i ] twice ; Excludes the element B [ i ] ; Function to find a subset sum whose sum is closest to K ; Traverse the array A [ ] ; Function Call ; Return the ans ; Input ; Function Call
let ans = Number . MAX_SAFE_INTEGER let mini = Number . MAX_SAFE_INTEGER function findClosestTarget ( i , curr , B , M , K ) { if ( Math . abs ( curr - K ) < mini ) { mini = Math . abs ( curr - K ) ; ans = curr ; } if ( Math . abs ( curr - K ) == mini ) { ans = Math . min ( ans , curr ) ; } if ( i >= M ) return ; findClosestTarget ( i + 1 , curr + B [ i ] , B , M , K ) ; findClosestTarget ( i + 1 , curr + 2 * B [ i ] , B , M , K ) ; findClosestTarget ( i + 1 , curr , B , M , K ) ; } function findClosest ( A , B , N , M , K ) { for ( let i = 0 ; i < N ; i ++ ) { findClosestTarget ( 0 , A [ i ] , B , M , K ) ; } return ans ; } let A = [ 2 , 3 ] ; let B = [ 4 , 5 , 30 ] ; let N = A . length ; let M = B . length ; let K = 18 ; document . write ( findClosest ( A , B , N , M , K ) ) ;