Two Sum Closest - aloalgo

Two Sum Closest

Medium

You are given an array of integers nums and a target integer target, find two integers in nums such that their sum is closest to target. Return the sum of these two integers. You can assume that there will always be exactly one solution.

Example 1

Inputs
nums = [-1, 2, 1, -4]
target = 1
Output
1
Explanation:

The sum -1 + 2 = 1. The difference between 1 and target (1) is 0, which is the smallest possible difference.

Example 2

Inputs
nums = [1, 0, -1]
target = 2
Output
1
Explanation:

The sum 0 + 1 = 1. The difference between 1 and target (2) is 1. Other sums like -1 + 0 = -1 (diff 3) or -1 + 1 = 0 (diff 2) are further from the target.

Example 3

Inputs
nums = [1, 2, 3, 4]
target = 8
Output
7
Explanation:

The sum 3 + 4 = 7. The difference between 7 and target (6) is 1. The sum 2 + 4 = 6, which is exactly the target. The sum 1 + 2 = 3. The closest sum is 7, as 3 + 4 = 7 is closest to 6 with diff 1, and 2 + 4 = 6 is exactly 6 with diff 0. Oh, the example states [1, 2, 3, 4], 6 and expected 7. This example is flawed. It should be 6 or change the target. Let me correct the example: [1, 2, 3, 4], 6. The sums are 1+2=3, 1+3=4, 1+4=5, 2+3=5, 2+4=6, 3+4=7. The closest to 6 is exactly 6. Let's make it [1, 2, 3, 4], 5. The sum 1+4=5 or 2+3=5 matches. Or [1, 2, 3, 4], 7 then 3+4=7 is exact. Let me adjust the example to correctly show 'closest' not necessarily 'exact'. Corrected example: nums = [1, 2, 3, 4], target = 8. Sorted: [1, 2, 3, 4]. Sums: 1+2=3, 1+3=4, 1+4=5, 2+3=5, 2+4=6, 3+4=7. Closest to 8 is 7. Diff = 1.

Loading...
Inputs
nums = [-1, 2, 1, -4]
target = 1
Output
1

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!