二分优化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 startTimeendTime 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
class Solution:
    def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
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
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
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];
    }
};

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EQUINOX1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值