Leetcode::Maximum Profit in Job Scheduling

point

Design

Big O(time)

Code

Top - Down

class Solution {
public:
    int n;
    vector<int> DP;
    vector<vector<int> > times;

    // DP[id] : suffix sum from id
    int dynamic(int id, vector<int>& startTime) {
        if (id == n) return 0;
        if (DP[id] != -1) return DP[id];

        int nxtId = lower_bound(startTime.begin(), startTime.end(), times[id][1]) - startTime.begin();
        int mx = max(times[id][2]+ dynamic(nxtId, startTime), dynamic(id+1, startTime));

        return DP[id] = mx;
    }

    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
        n = startTime.size();
        DP = vector<int> (n + 1, -1);
        

        // It's possible to push one array into vector !
        for(int i = 0; i < n; i++) times.push_back({startTime[i], endTime[i], profit[i]});

        sort(times.begin(), times.end());

        for(int i = 0; i < n; i++) {
            startTime[i] = times[i][0];
        }
        
        return dynamic(0, startTime);
    }
};

Botton - up

class Solution {
public:
    int n;
    vector<int> DP;
    vector<vector<int> > times; // [0] : start, [1] : end, [2] : profit

    // DP[id] : suffix sum from id
    int dynamicBottomUp(vector<int>& startTime) {

        for (int i = n - 1; i >= 0; i--) {
            int curProfit = 0; // including [i]
            int nxtId = lower_bound(startTime.begin(), startTime.end(), times[i][1]) - startTime.begin();
    
            if (nxtId == n)
                curProfit = times[i][2];
            else
                curProfit = times[i][2] + DP[nxtId];
            
            // including [i] vs skipping [i]
            if (i == n-1)
                DP[i] = curProfit;
            else
                DP[i] = max(curProfit, DP[i+1]);

        }


        return DP[0];
    }

    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
        n = startTime.size();
        DP = vector<int> (n + 1, -1);
        

        // It's possible to push one array into vector !
        for(int i = 0; i < n; i++) times.push_back({startTime[i], endTime[i], profit[i]});

        sort(times.begin(), times.end());

        for(int i = 0; i < n; i++) {
            startTime[i] = times[i][0];
        }
        
        return dynamicBottomUp(startTime);
    }
};