Given an integer array nums of length at least 3 and an integer target, choose three distinct indices i, j, and k and return the sum nums[i] + nums[j] + nums[k] whose value is closest to target.
You only need to return the closest sum, not the actual triplet.
Input / output
nums: int[], target: intintExamples
nums = [-1, 2, 1, -4], target = 1 returns 2 because (-1 + 2 + 1) = 2, which is closest to 1.nums = [0, 0, 0], target = 1 returns 0.nums = [1, 2, 4], target = 8 returns 7 because that is the only possible triplet sum.Constraints
3 <= nums.length <= 500-1000 <= nums[i] <= 1000-10^4 <= target <= 10^4target in the test data, so no tie-breaking rule is needed between two different sums.Follow-up
Can you improve the brute-force O(n^3) search by sorting the array first and then using a two-pointer scan for each fixed first value?