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:

  1. Initialize the table with zeros: dp[0][j] = 0 for all j.
  2. Fill in the base cases: dp[i][0] = 0 for all i, and dp[0][j] = 0 for all j.
  3. For each interval i from 1 to n-1, and for each j from 1 to m-1:
    • If the current interval's end time is less than or equal to the j-th interval's start time, then we can safely consider this interval without worrying about overlapping intervals. In this case, we update dp[i][j] = max(dp[i][j], dp[i-1][k] + profit[i]), where k is the maximum index such that end_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.
  4. 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

View on GeeksforGeeks
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];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.