Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1235. Maximum Profit in Job Scheduling

Rain Hu

1235. Maximum Profit in Job Scheduling


一、題目

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.

Example 1:
smaple1

Example 2: sample2

Example 3: sample3

Constraints:


二、分析

三、解題

int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
    map<int,int> dp;
    vector<vector<int>> job;
    int n = startTime.size();
    for (int i = 0; i < n; i++) {
        job.push_back({endTime[i], startTime[i], profit[i]});
    }
    sort(job.begin(), job.end());   // sort by endTime
    dp.insert({0,0});               // 省去處理 out of range
    int res = 0;
    for (int i = 0; i < n; i++) {
        auto it = dp.upper_bound(job[i][1]);    // > startTime
        it--;                                   // <= startTime
        int last = it->second;
        int val = last + job[i][2];             // 由當前最大收益往上累積
        int pos = job[i][0];
        if (val < res) continue;  // 若當前最大收益比歷史最大收益還小,則跳過不記錄

        dp[pos] = max(dp[pos], val);            // 更新當前最大收益
        res = max(dp[pos], res);                // 更新歷史最大收益
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2485. Find the Pivot Integer
Next
[LeetCode] 1143. Longest Common Subsequence