Created
March 24, 2021 13:23
-
-
Save rohanjai777/9e183b6c2f0b6e0c5d86328a190015c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int threeSumClosest(int[] arr, int b) { | |
Arrays.sort(arr); | |
int mindiff = Integer.MAX_VALUE; | |
int close_sum = 0; | |
for(int i=0;i<arr.length;i++){ | |
int v = arr[i]; | |
int j=i+1; | |
int k=arr.length-1; | |
while(j<k){ | |
long sum = arr[j]+arr[k]+v; | |
int diff = (int)Math.abs(b-sum); | |
if(diff<mindiff){ | |
mindiff = diff; | |
close_sum = (int)sum; | |
} | |
if(sum < b){ | |
j++; | |
}else if(sum>b){ | |
k--; | |
}else{ | |
return close_sum; | |
} | |
} | |
} | |
return close_sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment