2023-09-11 LeetCode每日一题(课程表 III)

2023-09-11每日一题

一、题目编号

630. 课程表 III

二、题目链接

点击跳转到题目位置

三、题目描述

这里有 n 门不同的在线课程,按从 1 到 n 编号。给你一个数组 courses ,其中 courses[i] = [durationi, lastDayi] 表示第 i 门课将会 持续 上 durationi 天课,并且必须在不晚于 lastDayi 的时候完成。

你的学期从第 1 天开始。且不能同时修读两门及两门以上的课程。

返回你最多可以修读的课程数目。

示例 1:
2023-09-11 LeetCode每日一题(课程表 III)_第1张图片

示例 2:
在这里插入图片描述

示例 3:
在这里插入图片描述
提示:

  • 1 <= courses.length <= 104
  • 1 <= durationi, lastDayi <= 104

四、解题代码

class Solution {
public:
    int scheduleCourse(vector<vector<int>>& courses) {
        sort(courses.begin(), courses.end(), [](const auto& c0, const auto& c1) {
            return c0[1] < c1[1];
        });

        priority_queue<int> q;
        
        int total = 0;

        for (const auto& course: courses) {
            int ti = course[0], di = course[1];
            if (total + ti <= di) {
                total += ti;
                q.push(ti);
            }
            else if (!q.empty() && q.top() > ti) {
                total -= q.top() - ti;
                q.pop();
                q.push(ti);
            }
        }

        return q.size();
    }
};

五、解题思路

(1) 运用优先队列和贪心的思想来解决问题。

你可能感兴趣的:(LeetCode每日一题,leetcode,算法,数据结构)