Find the triplet sum in an integer array that is closest to a target value.
Problem
Given an integer array nums and an integer target, choose three distinct elements from nums whose sum is as close as possible to target.
Return the sum of the chosen triplet.
If multiple triplets are equally close, any one of their sums is acceptable.
Goal
You are not asked to return the indices or the triplet itself, only the closest sum.
Input Format
nums: an array of integerstarget: an integer
You may assume nums contains at least 3 numbers.
Output Format
- Return a single integer: the sum of three numbers whose value is closest to
target.
Constraints
- Choose exactly 3 distinct elements from
nums. numscontains at least 3 integers.- The answer is guaranteed to fit in a 32-bit signed integer for typical interview settings.
Example 1
Input
nums = [-1, 2, 1, -4], target = 1
Output
2
Explanation
The triplet [-1, 2, 1] has sum 2, which is closest to 1. Another valid example is not closer than 2.
Example 2
Input
nums = [0, 0, 0], target = 1
Output
0
Explanation
The only possible triplet sum is 0, so it is the closest.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.