630. Course Schedule III

4 篇文章 0 订阅
2 篇文章 0 订阅
题目:

There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.

Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

大概为,根据所给数组,求最大的排课数量是多少;

大神的算法:

public int scheduleCourse(int[][] courses) {
        Arrays.sort(courses,(a,b)->a[1]-b[1]); //Sort the courses by their deadlines (Greedy! We have to deal with courses with early deadlines first)
        PriorityQueue<Integer> pq=new PriorityQueue<>((a,b)->b-a);
        int time=0;
        for (int[] c:courses) 
        {
            time+=c[0]; // add current course to a priority queue
            pq.add(c[0]);
            if (time>c[1]) time-=pq.poll(); //If time exceeds, drop the previous course which costs the most time. (That must be the best choice!)
        }        
        return pq.size();
    }

自己的理解: 我们可以从最后的结果来思考,如果我们已知最后的结果,那么我们可以推断最后结果的形式,以此来确定应该以什么方式排课。从推测结果可知,dth越小,数组越是排在前列,因为要求要有最多的课,如果dth小的排在后边,会浪费时间。所以可以对dth从小到大排列,然后从中依次挑选,然后检查是否可以排课,如果可以排课,那么当前数组中最大的dth一定大于等于所用时间,否则,则把已排课中占用时间最大的课,排除。然后再进行下一次挑选。这样到最后,得到的课数量便是能排课的最大数量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值