Friday, September 11, 2020

[Amazon Question] Find a triplet in an array that sum to the closest to given value

Problem: Given an array nums of n integers 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:

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).

Approach: We can sort the array and then can use 2 pointers approach.


Implementation in C#:

        public int ThreeSumClosest(int[] nums, int target)
        {
            int diff = int.MaxValue, result = int.MaxValue;
            if (nums == null && nums.Length < 3)
            {
                return result;
            }

            Array.Sort(nums);

            for (int i = 0; i < nums.Length; ++i)
            {
                int low = i + 1, high = nums.Length - 1;

                while(low < high)
                {
                    int sum = nums[i] + nums[low] + nums[high];
                    if (diff > Math.Abs(target - sum))
                    {
                        diff = Math.Abs(target - sum);
                        result = sum;
                        if (diff == 0)
                        {
                            return result;
                        }
                    }

                    if (sum < target)
                    {
                        ++low;
                    }
                    else
                    {
                        --high;
                    }
                }
            }

            return result;
        }


Complexity: O(n^2)

No comments:

Post a Comment