Problem description

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^4

After the pattern

Now solve one you haven't seen.

Three-Weight Ballast Trim is our own problem on the technique behind 3Sum Closest: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free