class Solution {
    public int smallestChair(int[][] times, int targetFriend) {
        int[] target = times[targetFriend];
        Arrays.sort(times, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return a[0] - b[0];
            }
        });
        int size = 0;
        for (int i = 0; i < times.length; i++) {
            if (times[i][0] == target[0]) {
                size = i;
                break;
            }
        }
        int[] arr = new int[size + 1];
        List<Integer> use = new ArrayList<>();
        int index = 0;
        int start = times[0][0];
        for (int[] time : times) {
            for (int i = 0; i < index; i++) {
                if (arr[i] > 0) {
                    arr[i] -= time[0] - start;
                    if (arr[i] <= 0) {
                        use.add(i);
                        Collections.sort(use);
                    }
                }
            }
            start = time[0];
            if (time[0] == target[0]) {
                return use.size() > 0 ? use.get(0) : index;
            }
            if (use.size() > 0) {
                arr[use.get(0)] = time[1] - time[0];
                use.remove(0);
            } else {
                arr[index] = time[1] - time[0];
                index++;
            }
        }
        return 0;
    }
}
//runtime:433 ms
//memory:46.5 MB
