Blogs Hub

by Sumit Chourasia | Oct 23, 2020 | Category :coding | Tags : algorithm array data-structure leetcode medium

3Sum Closest - Array - Medium - LeetCode

3Sum Closest - Array - Medium - LeetCode

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

Constraints:

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

public class Solution {
    public int ThreeSumClosest(int[] nums, int target) {
        Array.Sort(nums);
        int minDiff = int.MaxValue;
        int minSum = 0;
        for(int i=0;i<nums.Length-2;i++){
            for(int j=i+1, k=nums.Length-1; j<k;){
                int sum = nums[i]+ nums[j]+ nums[k];                
                int diff = Math.Abs(sum-target);                
                if(minDiff>diff){
                    minDiff = diff;
                    minSum = sum;
                }
                if(sum > target){
                    k--;
                }
                else if(sum < target){
                    j++;
                }
                else{
                    // if sum is equal to target
                    return target;
                }
            }
        }
        
        return minSum;
    }
}

Time Complexity: O(n^2+nlogn) = O(n^2)

Space Complexity: O(1)

Contributed By: Sumit Chourasia
Array Nesting - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Valid Triangle Number - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Richest Customer Wealth - String - Easy - LeetCode