Skip to content
Onsite

3Sum Closest

MediumP2Coding

Given an integer array nums of at least three elements and an integer target, choose three elements at different indices so that their sum is as close to target as possible. Return that sum.

The input is built so that the closest sum is unique.

Example 1

Input
nums = [-1,2,1,-4], target = 1
Output
2

Example 2

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

Example 3

Input
nums = [1,1,1,0], target = -100
Output
2

Constraints

  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4
  • Exactly one closest sum exists.

Hints

Run checks the 3 visible tests, Submit all 10.