九 1343. 挤牛奶 (区间合并)

1343. 挤牛奶 (区间合并)

思路:将挤奶时间段按开始时间重新排序,然后合并区间右侧和下一区间左侧重合的区间,当不重合时,计算最长连续挤奶时间以及最长连续无人挤奶时间。

import java.util.*;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] a = new int[n][2];
        IntStream.range(0, n).forEach(i -> {
            int left = sc.nextInt();
            a[i][0] = left;
            int right = sc.nextInt();
            a[i][1] = right;
        });
        int res1 = 0, res2 = 0;
        Arrays.sort(a, Comparator.comparingInt(item -> item[0]));
        int left = a[0][0];
        int right = a[0][1];
        for (int i = 1; i < n; i++) {
            if (a[i][0] <= right) {
                right = Math.max(right, a[i][1]);
            }
            else {
                res1 = Math.max(res1, right - left);
                res2 = Math.max(res2, a[i][0] - right);
                left = a[i][0];
                right = a[i][1];
            }
        }
        res1 = Math.max(res1, right - left);
        System.out.println(res1 + " " + res2);
    }
}
posted @ 2024-03-25 21:07  he0707  阅读(10)  评论(0)    收藏  举报