You are given an integer array and a target value. Pick exactly three elements from three different positions so that their sum lands as near to the target as possible.
Return that closest achievable sum. The inputs are chosen so that exactly one closest sum exists.
Example 1
Input: nums = [-1, 2, 1, -4], target = 1
Output: 2
The triplet (-1, 2, 1) totals 2, which is the nearest value to the target of 1.
Example 2
Input: nums = [0, 0, 0], target = 5
Output: 0
The only triplet sums to 0, so that becomes the closest reachable total.
Constraints
3 ≤ nums.length ≤ 5 * 10^2-10^3 ≤ nums[i] ≤ 10^3-10^4 ≤ target ≤ 10^4See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI