PostAddsense


SkipRope Topcoder



import java.util.Arrays;

public class SkipRope
{
    public int[] partners(int[] candidates, int height) {
        Arrays.sort(candidates);

        int[] res = new int[2];

        int best = 201;
        for (int i = 0; i < candidates.length-1; i++) {
            if (Math.abs(candidates[i] - height) + Math.abs(candidates[i+1] - height) <= best) {
                best = Math.abs(candidates[i] - height) + Math.abs(candidates[i+1] - height);
                res[0] = candidates[i]; res[1] = candidates[i+1];
            }
            else break;
        }

        return res;
    }
}


Explanation

candidate 배열을 정렬하고 순차적으로 인접한 두 요소의 합을 best와 비교해 나간다. best보다 작으면 best에 이 값을 저장하고, res 배열에 두 후보자의 값을 저장한다. 배열을 정렬했기 때문에 두 요소의 합이 best보다 크면 배열에 더 이상 작은 값이 없으므로 for문을 빠져 나온다.