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

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.

```
```
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
// ============================================================================// Author: Kenneth Perkins// Date: Oct 28, 2021// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to get 3 numbers closest to target value// ============================================================================public class Solution { public int ThreeSumClosest(int[] nums, int target) { var result = 0; // Keep track of the solution closest to the target var closestDifference = int.MaxValue; // Sort the array Array.Sort(nums); // Loop through numbers for (int index = 0; index < nums.Length; ++index) { // Skip duplicates if (index > 0 && nums[index] == nums[index - 1]) { continue; } // Find 3 sum combination closest to the target value var startIndex = index + 1; var endIndex = nums.Length - 1; while (startIndex < endIndex) { // Get the sum var sum = nums[index] + nums[startIndex] + nums[endIndex]; // Determine how close the sum is to the target value var difference = Math.Abs(target - sum); if (difference < closestDifference) { closestDifference = difference; result = sum; } // An exact match is found, exit if (difference == 0) { break; // Sum is less than target } else if (sum < target) { ++startIndex; // Sum is greater than target } else { --endIndex; } } // An exact match is found, exit if (closestDifference == 0) { break; } } return result; }}// http://programmingnotes.org/

**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

## Leave a Reply