Leetcode 3Sum Closest problem solution in C# programming

In the Leetcode 3Sum Closest problem solution in C# programming 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.

Leetcode 3Sum Closest problem solution in C# programming

public class Solution {
    public int ThreeSumClosest(int[] nums, int target) {
       Array.Sort(nums);
       int i=0,length=nums.Length,closest=Int32.MaxValue;
       while(i<length-2){
           int j=i+1;
           int k=length-1;
           while(j<k){    
               int sum= nums[i]+nums[j]+nums[k];
               if((Math.Abs(target-sum))<(Math.Abs(target-closest))){
                  closest= sum;
               }
               if(sum == target) return sum;
               if (sum<target) while(j<k && nums[j+1]==nums[j++]);
               if (sum>target) while(j<k && nums[k-1]==nums[k--]);
           }
           while(i<length-2 && nums[i+1]==nums[i++]);
       } 
       return closest;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *