import java.util.Arrays;
import java.lang.Math;
public class Solution {
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort(num);
int closet = num[0] + num[1] + num[2];
for(int i = 0; i< num.length; i++){
for(int j = i+1, k = num.length -1;j < k;)
{
int sum = num[i] + num[j] + num[k];
if(sum == target){
return target;
}
else if( sum > target){
closet = Math.abs( target - closet) > Math.abs( target - sum ) ? sum : closet;
k--;
}
else{
closet = Math.abs(target - closet) > Math.abs( target - sum ) ? sum : closet;
j++;
}
}
}
return closet;
}
}