方法一:
class Solution {
public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
int n = startTime.length;
// 存储的是第i份工作的最大利润
int[] dp = new int[n];
// 存储的是按结束日期升序排列的第i份工作的信息
Work[] works = new Work[n];
for(int i = 0; i < n; i++) {
works[i] = new Work(startTime[i], endTime[i], profit[i]);
}
Arrays.sort(works);
for(int i = 0; i < n; i++) {
if(i == 0) {
dp[i] = works[i].profit;
} else {
// 前一份与之不重叠的工作的报酬
int pre = 0;
// 向前寻找第一个结束时间在本次工作开始时间之前的工作
for(int j = i - 1; j >= 0; j--) {
if(works[j].endTime <= works[i].startTime) {
pre = dp[j];
break;
}
}
dp[i] = Math.max(dp[i - 1], pre + works[i].profit);
}
}
return dp[n - 1];
}
// 兼职工作实体类,通过完成工作日期排序
class Work implements Comparable<Work> {
public int startTime, endTime, profit;
public Work(int startTime, int endTime, int profit) {
this.startTime = startTime;
this.endTime = endTime;
this.profit = profit;
}
public int compareTo(Work other) {
return Integer.compare(this.endTime, other.endTime);
}
}
}