-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumClosestSolver.cs
More file actions
55 lines (46 loc) · 1.7 KB
/
ThreeSumClosestSolver.cs
File metadata and controls
55 lines (46 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
namespace CodeChallenge
{
public class ThreeSumClosestSolver
{
public int ThreeSumClosest(int[] nums, int target)
{
// Sort the array to use the two-pointer technique
Array.Sort(nums);
int n = nums.Length;
int closestSum = int.MaxValue;
// Loop through each number in the array
for (int i = 0; i < n - 2; i++)
{
int left = i + 1;
int right = n - 1;
// Use two pointers to find the best possible sum with nums[i]
while (left < right)
{
int currentSum = nums[i] + nums[left] + nums[right];
// If the currentSum is closer to the target, update closestSum
if(Math.Abs(target - currentSum) < Math.Abs(target - closestSum))
{
closestSum = currentSum;
}
// Adjust pointers based on the current sum's relation to the target
if (currentSum < target)
{
// Move left pointer right to increase sum
left++;
}
else if (currentSum > target)
{
// Move right pointer left to decrease sum
right--;
}
else
{
// If found an exact match, return immediately
return currentSum;
}
}
}
return closestSum;
}
}
}