1235. Maximum Profit in Job Scheduling
Previous1229. Meeting SchedulerNext1239. Maximum Length of a Concatenated String with Unique Characters
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
// Time Limit Error
class Solution {
private class Job implements Comparable<Job> {
int startTime;
int endTime;
int profit;
Job(int startTime, int endTime, int profit) {
this.startTime = startTime;
this.endTime = endTime;
this.profit = profit;
}
public int compareTo(Job otherJob) {
int d = this.endTime-otherJob.endTime;
return d == 0? (this.startTime-otherJob.startTime): d;
}
}
public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
int n = profit.length;
Job[] jobs = new Job[n];
for(int i = 0; i < n; i++) {
jobs[i] = new Job(startTime[i], endTime[i], profit[i]);
}
Arrays.sort(jobs);
int[] dp = new int[n];
int maxProfit = 0;
for(int i = 0; i < n; i++) {
dp[i] = jobs[i].profit;
for(int j = 0; j < i; j++) {
if(jobs[j].endTime <= jobs[i].startTime) {
dp[i] = Math.max(dp[i], jobs[i].profit+dp[j]);
}
}
maxProfit = Math.max(maxProfit, dp[i]);
}
return maxProfit;
}
}/**
* Time complexity :
* Space complexity :
*/
class Solution {
private class Job implements Comparable<Job> {
int startTime;
int endTime;
int profit;
Job(int startTime, int endTime, int profit) {
this.startTime = startTime;
this.endTime = endTime;
this.profit = profit;
}
public int compareTo(Job otherJob) {
return this.endTime-otherJob.endTime;
}
}
public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
int n = profit.length;
Job[] jobs = new Job[n];
for(int i = 0; i < n; i++) {
jobs[i] = new Job(startTime[i], endTime[i], profit[i]);
}
Arrays.sort(jobs);
int[] dp = new int[n];
dp[0] = jobs[0].profit;
for(int i = 1; i < n; i++) {
dp[i] = Math.max(jobs[i].profit, dp[i-1]);
for(int j = i-1; j >= 0; j--) {
if(jobs[j].endTime <= jobs[i].startTime) {
dp[i] = Math.max(dp[i], jobs[i].profit+dp[j]);
break;
}
}
}
return dp[n-1];
}
}