package ArrayProb;

import java.util.Arrays;

public class ThreeSumClosest {
	public static void main(String[] args) {
		int[] A = {-1, 2, 1, 4};
		System.out.println(threeSumClosest(A, 1));
	}
	
	public static int threeSumClosest(int[] num, int target) {
        if (num.length == 0 || num == null || num.length < 3) return -1;
        Arrays.sort(num);
        int min = num[0] + num[1] + num[2];
        for (int i = 0; i < num.length; i++) {
            int j = i + 1;
            int end = num.length - 1;
            while (j < end) {
                int sum = num[i] + num[j] + num[end];
                if (Math.abs(sum - target) < Math.abs(min - target)) min = sum;
                if (sum < target) j++;
                else end--;
            }
        }
        return min;
    }
}
