Three Numbers Closest to a Target

MediumTwo Pointers≈ 35 min

You are given a list of integers nums and a target. Choose three numbers at three different indexes whose total is as close to target as possible, and return that total.

If two totals are equally close, one below the target and one above, return the smaller one.

Examples

text
nums = [-1, 2, 1, -4], target = 1      →  2
nums = [0, 0, 0], target = 1           →  0
nums = [1, 1, 1, 0], target = 100      →  3
nums = [4, -3, 8, 1, 6], target = 5    →  4

In the first example -1 + 2 + 1 = 2 is one away from 1, and no three numbers come closer. In the last, no three numbers add up to exactly 5; -3 + 1 + 6 = 4 and -3 + 8 + 1 = 6 are both one away, and the smaller total wins.

Constraints

  • Between 3 and 400 numbers, each between -1,000 and 1,000.
  • Aim for O(n²): there are about n³ / 6 ways to choose three numbers, and you should not try them all.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.