C# || 3Sum Closest – How To Get 3 Numbers In Array Closest Equal To Target Value Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to get 3 numbers in an array closest equal to target value using C#.


1. 3 Sum Closest – Problem Statement

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Example 1:


Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Example 2:


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


2. 3 Sum Closest – Solution

The following is a solution which demonstrates how to get 3 numbers in an array closest equal to target value.

This solution uses the two pointer technique to find combinations.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


2
0

Was this article helpful?
👍 YesNo

Leave a Reply