Find the Triplet Sum Nearest to a Target Value

Implement closestTripletSum

Given an integer array nums and an integer target, find the sum of exactly three different elements that lands as close as possible to target. Return that sum itself — not the triplet. You may assume there's exactly one distance-minimizing sum to report. For example, with nums = [-6, 1, 1, 1, 8] and target = 2, the triplet 1 + 1 + 1 = 3 is only 1 away from the target, closer than anything else the array can produce, so the answer is 3.

Example 1:

Input: nums = [-6,1,1,1,8], target = 2

Output: 3

Example 2:

Input: nums = [0,0,0], target = 1

Output: 0

Example 3:

Input: nums = [1,2,3,4], target = 6

Output: 6

+ 4 hidden test cases run on Submit.

Constraints:

  • 3 ≤ nums.length ≤ 500
  • -1000 ≤ nums[i] ≤ 1000
  • -10⁴ ≤ target ≤ 10⁴

nums =

[-6, 1, 1, 1, 8]

target =

2