二分优化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、思路分析

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

这里按照右端点升序排序

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

那么fi + 1 = max(fi, fj + profiti)

即第 i 个工作选或不选,j要满足endTimej <= startTimei,这个由于我们已经按照右端点升序排序,所以可以二分查找来快速找到 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];
    }
};
相关推荐
毕竟是shy哥25 分钟前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
M78佐菲28 分钟前
Linux学习笔记:TCP协议
linux·笔记·学习·tcp/ip·算法
圣保罗的大教堂1 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
晊晌_h2 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦2 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考3 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客3 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
小白羊丨6 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F8 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
lisin-lee-cooper8 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法