Loading content...
You are given an integer array nums containing n elements and an integer target value. Your task is to identify three distinct elements from the array (elements at different indices) such that their sum is as close as possible to the target.
Return the sum of the three selected integers.
You may assume that each input will have exactly one unique solution — meaning there will always be precisely one triplet whose sum is closest to the target.
nums = [-1, 2, 1, -4]
target = 12The triplet that produces the sum closest to the target is (-1, 2, 1). Their sum is -1 + 2 + 1 = 2, which is only 1 unit away from the target value of 1. No other triplet gets closer to the target.
nums = [0, 0, 0]
target = 10The only possible triplet consists of all three zeros: 0 + 0 + 0 = 0. Although the target is 1, the closest achievable sum is 0 since that is the only triplet available.
nums = [1, 2, 3, 4, 5]
target = 99Multiple triplets are possible here: (1,2,3)=6, (1,2,4)=7, (1,2,5)=8, (1,3,4)=8, (1,3,5)=9, (1,4,5)=10, (2,3,4)=9, (2,3,5)=10, (2,4,5)=11, (3,4,5)=12. The triplets (1,3,5) and (2,3,4) both sum to exactly 9, which equals the target. Since this is the closest possible (difference of 0), we return 9.
Constraints