MysteriousLifeGuards

 avatar
unknown
java
4 years ago
2.1 kB
6
Indexable
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class MysteriousSafeguards {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Integer[][] a = new Integer[n][2];
        for (int i = 0; i < n; i++) {
            a[i][0] = scanner.nextInt();
            a[i][1] = scanner.nextInt();
        }
        Arrays.sort(a, new Comparator<Integer[]>() {
            @Override
            public int compare(Integer[] a, Integer[] b) {
                int xEqual = a[0].compareTo(b[0]);
                if (xEqual != 0) return xEqual;
                return a[1].compareTo(b[1]);
            }
        });
        int maxOverlap = Integer.MIN_VALUE;
        int index = -1;

        for (int i=0; i < n; i++) {
            int overlap = 0;
            int currStart = a[i][0];
            int currEnd = a[i][1];
            if (i-1 >= 0) {
                int prevStart = a[i-1][0];
                int prevEnd = a[i-1][1];
                if (prevEnd > currStart) {
                    overlap += prevEnd - currStart;
                }
            }
            if (i+1 < n) {
                int nextStart = a[i+1][0];
                int nextEnd = a[i+1][1];
                if (nextStart < currEnd) {
                    overlap += currEnd - nextStart;
                }
            }
            if (overlap > maxOverlap) {
                maxOverlap = overlap;
                index = i;
            }
        }

        int maxTimeSoFar = Integer.MIN_VALUE;
        int timeCount = 0;

        for (int i = 0; i < n; i++) {
            if (i != index) {
                if (a[i][0] > maxTimeSoFar) {
                    maxTimeSoFar = a[i][1];
                    timeCount += a[i][1] - a[i][0];
                } else if (a[i][1] > maxTimeSoFar) {
                    timeCount += a[i][1] - maxTimeSoFar;
                    maxTimeSoFar = a[i][1];
                }
            }
        }
        System.out.println(timeCount);
    }
}
Editor is loading...