Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- pair<int, int> getMaxProfit(int level, int timeElapsed, vector<pair<int, int> > &jobs, vector<vector<pair<int, int> > > &memo){
- //BASE CASE HANDLED IMPLICITLY IN LOOP (we never call on invalid levels or out of bounds)
- //memo check
- if(memo[level][timeElapsed] != make_pair(-1, -1)){
- return memo[level][timeElapsed];
- }
- //maximum profit at current level
- int maxProfit = 0;
- int maxCount = 0;
- //to check if the LOOP ran, if not add profit of current level job EXPLICITLY before returning
- bool flag = false;
- for(int i = level + 1; i < jobs.size(); i++){
- //mark flag true
- flag = true;
- if(timeElapsed + 1 < jobs[i].first){
- // cout << jobs[level].second << "->" << jobs[i].second << '\n';
- auto res = getMaxProfit(i, timeElapsed + 1, jobs, memo);
- //found a combination with more profit, so update maxProfit and size of the sequence.
- if(res.second + jobs[level].second > maxProfit){
- //adding the profit of current level & adding the current level to the subset
- maxProfit = jobs[level].second + res.second;
- maxCount = 1 + res.first;
- }
- }
- }
- //loop didn't run, ADD PROFIT of CURRENT LEVEL JOB EXPLICITLY
- //maxCount = 1 (as the size of the sequence formed level onwards(including level) is 1)
- //no jobs scheduled after the current level, so the profit from recursion starting from level is 0, but the current level job is already scheduled
- //whose profit must be added
- //When the loop doesn't run, we add the value of current level EXPLICITLY (so here values tracked are profit and size)
- if(!flag){
- //starting from level, only 1 job scheduled, so the profit of that job and size = 1; is maxProfit and maxCount respectively
- maxProfit = jobs[level].second;
- maxCount = 1;
- }
- return memo[level][timeElapsed] = {maxCount, maxProfit};
- }
- vector<int> jobSequencing(vector<int> &deadline, vector<int> &profit) {
- // code here
- vector<pair<int, int> > jobs;
- for(int i = 0; i < deadline.size(); i++){
- jobs.emplace_back(deadline[i], profit[i]);
- }
- //ORDER OF JOBS AFTER SORTING
- //jobs[deadline1] < jobs[deadline2], jobs[deadline1] = jobs[deadline2], then jobs[profit1] < jobs[profit2]
- sort(jobs.begin(), jobs.end());
- // for(auto i : jobs){
- // cout << i.first << " ";
- // }
- // cout << '\n';
- // for(auto i : jobs){
- // cout << i.second << " ";
- // }
- // cout << '\n';
- int maxProfit = 0;
- int maxCount = 0;
- int count = 0;
- vector<vector<pair<int, int> > > memo(deadline.size(), vector<pair<int, int> >(deadline.size(), {-1, -1}));
- //give every job the chance to be the first in the subset
- for(int i = 0; i < jobs.size(); i++){
- auto iRes = getMaxProfit(i, 0, jobs, memo);
- if(iRes.second > maxProfit){
- maxProfit = max(maxProfit, iRes.second);
- maxCount = max(maxCount, iRes.first);
- }
- }
- vector<int> res{maxCount, maxProfit};
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment