713370. Maximum Profit By Choosing A Subset Of Intervals
Medium
Maximum Profit By Choosing A Subset Of Intervals
Summary
The problem is to find a subset of intervals such that the maximum profit can be achieved. The given intervals have start and end times, and their corresponding profits. The goal is to choose a subset of these intervals in a way that maximizes the total profit.
Detailed Explanation
To solve this problem, we will use dynamic programming (DP). We create a 2D table dp where dp[i][j] represents the maximum profit that can be achieved considering the first i intervals and only using the first j of them.
Here is the step-by-step breakdown:
- Initialize the table with zeros:
dp[0][j] = 0for allj. - Fill in the base cases:
dp[i][0] = 0for alli, anddp[0][j] = 0for allj. - For each interval
ifrom 1 ton-1, and for eachjfrom 1 tom-1:- If the current interval's end time is less than or equal to the
j-thinterval's start time, then we can safely consider this interval without worrying about overlapping intervals. In this case, we updatedp[i][j] = max(dp[i][j], dp[i-1][k] + profit[i]), wherekis the maximum index such thatend_time[k] <= start_time[j]. - Otherwise, we can't consider this interval because it overlaps with some other intervals.
In this case, we update
dp[i][j] = max(dp[i][j], dp[i-1][j]). This means we don't include the current interval in our solution.
- If the current interval's end time is less than or equal to the
- Finally, return
max(dp[n-1][m-1])as the maximum profit that can be achieved.
Time complexity: O(nm) Space complexity: O(nm)
Optimized Solutions
Java
public int maxProfit(int[][] intervals) {
int n = intervals.length;
int m = intervals[0].length;
int[][] dp = new int[n][m];
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (intervals[i][1] <= intervals[j-1][0]) {
dp[i][j] = Math.max(dp[i-1][j], intervals[i][2]);
} else {
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n-1][m-1];
}