Problem 338406 · medium · Level 03 Linear Management & Searching

Three Cards Nearest the Call

two pointers · sorting · k-sum

In a card game every card carries an integer, possibly negative, and your hand nums holds at least three cards. You must lay down exactly three different cards (three distinct positions in nums) and want their total to land as near as possible to the number target the dealer calls. Return that total. If two different totals are equally near, return the smaller total.

Examples

Input:  nums = [5, -2, 3, -6], target = 1
Output: 2
Explanation: 5 + 3 + (-6) = 2 is one away from 1.

Input:  nums = [1, 1, 1, 0], target = 100
Output: 3

Input:  nums = [0, 2, 4, 6], target = 7
Output: 6
Explanation: 0 + 2 + 4 = 6 and 0 + 2 + 6 = 8 are both one away; the smaller sum wins.

Constraints

  • Target: O(n^2) time after sorting, O(1) extra space.

Goals

  • Fix one element and run a converging two-pointer scan on the rest
  • Track the closest sum with a deterministic tie-break
Starting Python…