/16. 3Sum Closest

16. 3Sum Closest

Medium
Arrays48.2% acceptance

Given an integer array arr of length n and an integer value target_sum, find three integers at distinct indices in arr such that their sum is closest to target_sum. Return the sum of these three integers. It is guaranteed that each input has exactly one solution.

Example 1

Input: arr = [3, 7, 8, 2], target_sum = 15

Output: 17

Explanation: The closest sum is 17 (3 + 7 + 7).

Example 2

Input: arr = [-5, 2, 4, 6], target_sum = 3

Output: 2

Explanation: The closest sum is 2 (-5 + 2 + 4).

Constraints

  • 3 <= len(arr) <= 500
  • -1000 <= arr[i] <= 1000 for all i
  • -104 <= target_sum <= 104
  • Each input has exactly one solution
Python (current runtime)

Case 1

Input: arr = [1, 4, 5, 9], target_sum = 10

Expected: 10

Case 2

Input: arr = [-2, 0, 1, 3], target_sum = 2

Expected: 2

Case 3

Input: arr = [10, 22, 5, -7], target_sum = 20

Expected: 17

Case 4

Input: arr = [100, 200, 300, 400], target_sum = 750

Expected: 900