Find the triplet sum in an integer array that is closest to a target value.
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.
You are not asked to return the indices or the triplet itself, only the closest sum.
nums: an array of integerstarget: an integerYou may assume nums contains at least 3 numbers.
target.nums.nums contains at least 3 integers.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
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.