# Python3 program of the above approach
# Stores the sum closest to K
ans = 10**8
# Stores the minimum absolute difference
mini = 10**8
# Function to choose the elements
# from the array B[]
def findClosestTarget(i, curr, B, M, K):
global ans, mini
# If absolute difference is less
# then minimum value
if (abs(curr - K) < mini):
# Update the minimum value
mini = abs(curr - K)
# Update the value of ans
ans = curr
# If absolute difference between
# curr and K is equal to minimum
if (abs(curr - K) == mini):
# Update the value of ans
ans = min(ans, curr)
# If i is greater than M - 1
if (i >= M):
return
# Includes the element B[i] once
findClosestTarget(i + 1, curr + B[i], B, M, K)
# Includes the element B[i] twice
findClosestTarget(i + 1, curr + 2 * B[i], B, M, K)
# Excludes the element B[i]
findClosestTarget(i + 1, curr, B, M, K)
# Function to find a subset sum
# whose sum is closest to K
def findClosest(A, B, N, M, K):
# Traverse the array A[]
for i in range(N):
# Function Call
findClosestTarget(0, A[i], B, M, K)
# Return the ans
return ans
# Driver Code
if __name__ == '__main__':
# Input
A = [2, 3]
B = [4, 5, 30]
N = len(A)
M = len(B)
K = 18
# Function Call
print (findClosest(A, B, N, M, K))
# This code is contributed by mohit kumar 29.