Wednesday, July 28, 2021

3Sum Closest

Problem;
Given an array of n integers and an integer target, find three integers in the array such that the sum is closest to the target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example, [-1, 2, 1, -4], target =  1, the sum should be 2, we choose (-1, 2, 1) sum is 2
Remember you have to
choose 3 integers, it's not required to they should be contiguous.

Approach:

We can solve this problem using the "Two pointers"
method. let's illustrate,

Here we tried to visualize two pointers method. While Calculating results we have to increase the left index or decrease the right index, simply we can do this by checking the case. When we got our answer, simply we will break the loop and will return our answer. Try to code your own, if you can't check the code given below.


No comments:

Post a Comment