Maximum Number of Events That Can Be Attended

给定一个数组,其中每个事件都有开始和结束时间。你可以从任何一天开始并结束一个事件,但一次只能参加一个。返回最多可以参加的事件数量。问题可以通过贪心算法解决,按事件开始时间排序,优先选择结束时间最早的事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.

Return the maximum number of events you can attend.

Example 1:

Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.

思路:这题是贪心算法,按照start排序之后,优先做deadline最早的活,扫描day,然后把所有满足trigger event的endday丢入pq中排序。然后把超过today的dueday的event丢掉,每次poll出来一个,然后扫描下一天。nlogn;

class Solution {
    public int maxEvents(int[][] events) {
        Arrays.sort(events, (a, b) -> (a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]));
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        int i = 0;
        int res = 0;
        for(int day = 1; day <= 100000; day++) {
            while(i < events.length && events[i][0] <= day) {
                pq.offer(events[i][1]);
                i++;
            }
            // 做完之后,要把pq里面,deadline超过今天的全部给踢掉;
            while(!pq.isEmpty() && pq.peek() < day) {
                pq.poll();
            }
            
            if(!pq.isEmpty()) {
                pq.poll();
                res++;
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值