Three Weights Closest to the Mark
Medium · Two Pointers · about 25 min
A shop scale needs a test load as close as possible to target grams. You have a list of weights nums (whole numbers, may be negative for this puzzle, may repeat). Pick three weights at three different positions and return the total that is closest to target.
- If two totals are equally close (one above and one below), return the smaller total.
- If there are fewer than three weights, raise an error (
ValueErrorin Python,throwin JavaScript).
Examples:
closest_trio_sum([-1, 2, 1, -4], 1) → 2 (-1 + 2 + 1)
closest_trio_sum([0, 2, 4, 6], 9) → 8 (8 and 10 are both 1 away; 8 is smaller)
Aim for O(n^2) time.
Hints
- Check the length first: fewer than three weights is an error.
- Sort a copy, fix the first weight, and use one pointer just after it and one at the end.
- Start the best total from a real trio (not 0). When a new total is equally close, keep the smaller one.
Learn the pattern first: the Two Pointers lesson.
More Two Pointers problems
- Two Gifts for One Card (Easy)
- Mirror Sign Check (Easy)
- Squash Repeated Readings (Easy)
- Ledger Entries That Cancel Out (Medium)
- Biggest Tank Between Two Posts (Medium)
- Rain Caught on a Rooftop Row (Hard)