二分优化dp,LeetCode 1235. Maximum Profit in Job Scheduling

目录

一、题目

1、题目描述

2、接口描述

python3

cpp

3、原题链接

二、解题报告

1、思路分析

2、复杂度

3、代码详解

python3

cpp


一、题目

1、题目描述

We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.

If you choose a job that ends at time X you will be able to start another job that starts at time X.

2、接口描述

python3
复制代码
python 复制代码
class Solution:
    def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
cpp
复制代码
cpp 复制代码
class Solution {
public:
    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {

    }
};

3、原题链接

1235. 规划兼职工作


二、解题报告

1、思路分析

经典区间问题,我们通常处理策略为按照某一端排序

这里按照右端点升序排序

然后定义状态 f[i] 为前 i 个工作所能取得的最大收益

那么f[i + 1] = max(f[i], f[j] + profit[i])

即第 i 个工作选或不选,j要满足endTime[j] <= startTime[i],这个由于我们已经按照右端点升序排序,所以可以二分查找来快速找到 j

2、复杂度

时间复杂度: O(nlogn)空间复杂度:O(n)

3、代码详解

python3
复制代码
python 复制代码
class Solution:
    def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
        p = sorted(zip(startTime, endTime, profit), key=lambda x:x[1])
        n = len(p)
        f = [0] * (n + 1)
        for i, (s, e, w) in enumerate(p):
            idx = bisect_left(p, s + 1, key=lambda x: x[1], hi = i)
            f[i + 1] = max(f[i], f[idx] + w)
        return f[n]
cpp
复制代码
cpp 复制代码
class Solution {
public:
    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
        int n = startTime.size();
        vector<array<int, 3>> p(n);
        for (int i = 0; i < n; i ++)
            p[i] = { startTime[i], endTime[i], profit[i] };

        sort(p.begin(), p.end(), [](const auto& a, const auto& b){
            return a[1] < b[1];
        });
        vector<int> f(n + 1);
        for (int i = 0; i < n; i ++){
            int idx = lower_bound(p.begin(), p.begin() + i, array<int, 3>{ 0, p[i][0] + 1, 0}, [](const auto& a, const auto& b){
                return a[1] < b[1];
            }) - p.begin();
            f[i + 1] = max(f[i], f[idx] + p[i][2]);
        }
        return f[n];
    }
};
相关推荐
东方佑27 分钟前
从字符串中提取重复子串的Python算法解析
windows·python·算法
西阳未落1 小时前
LeetCode——二分(进阶)
算法·leetcode·职场和发展
通信小呆呆1 小时前
以矩阵视角统一理解:外积、Kronecker 积与 Khatri–Rao 积(含MATLAB可视化)
线性代数·算法·matlab·矩阵·信号处理
CoderCodingNo2 小时前
【GESP】C++四级真题 luogu-B4068 [GESP202412 四级] Recamán
开发语言·c++·算法
一个不知名程序员www2 小时前
算法学习入门---双指针(C++)
c++·算法
Shilong Wang3 小时前
MLE, MAP, Full Bayes
人工智能·算法·机器学习
Theodore_10223 小时前
机器学习(6)特征工程与多项式回归
深度学习·算法·机器学习·数据分析·多项式回归
知花实央l3 小时前
【算法与数据结构】拓扑排序实战(栈+邻接表+环判断,附可运行代码)
数据结构·算法
lingling0093 小时前
机械臂动作捕捉系统选型指南:从需求到方案,NOKOV 度量光学动捕成优选
人工智能·算法
吃着火锅x唱着歌3 小时前
LeetCode 410.分割数组的最大值
数据结构·算法·leetcode