How to find the quadruplet that is close to target using C#?


Two Pointers pattern and is similar to quadruplet Sum to Zero. We can follow a similar approach to iterate through the array, taking one number at a time. At every step, we will save the difference between the quadruplet and the target number, and at each step we will compare it with the minimum target difference so far, so that in the end, we can return the triplet with the closest sum.

Time complexity

Sorting the array will take O(N* logN). Overall fourSumClosest() will take O(N * logN + N^3), which is asymptotically equivalent to O(N^3).

Space complexity

The space complexity of the above algorithm will be O(N) which is required for sorting.

Example

public class Arrays{
   public int FourSumClosestToTarget(int[] nums, int target){
      if (nums == null || nums.Length == 0){
         return -1;
      }
      int[] newNums = nums.OrderBy(x => x).ToArray();
      int initialSum = newNums[0] + newNums[1] + newNums[2] + newNums[3];
      for (int i = 0; i < nums.Length; i++){
         for (int j = i; j < nums.Length; j++){
            int left = j + 1;
            int right = nums.Length - 1;
            while (left < right){
               int nearestSum = newNums[i] + newNums[j] + newNums[left] + newNums[right];
               if (nearestSum < initialSum){
                  initialSum = nearestSum;
               }
               if (nearestSum == target){
                  return nearestSum;
               }
               else if (nearestSum < target){
                  left++;
               }
               else{
                  right--;
               }
            }
         }
      }
     return initialSum;
   }
}

static void Main(string[] args){
   Arrays s = new Arrays();
   int[] nums = { 1,0,-1,0,-2,2 };
   var ss = FourSumClosestToTarget(nums,0);
   Console.WriteLine(ss);
}

Output

0

Updated on: 17-Aug-2021

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements