Weighted Activity Selection - Problem

You are given n activities where each activity has a start time, end time, and profit. Your goal is to select the maximum number of non-overlapping activities that maximizes the total profit.

Two activities are considered overlapping if one starts before the other ends. You need to use Dynamic Programming with Binary Search to solve this efficiently.

Input Format:

  • An array of activities where each activity is represented as [start_time, end_time, profit]

Output: Return the maximum profit achievable by selecting non-overlapping activities.

Input & Output

Example 1 — Basic Case
$ Input: activities = [[1,3,50],[2,5,20],[4,6,70],[6,8,30]]
Output: 120
💡 Note: Select activities [1,3,50] and [4,6,70]. They don't overlap (first ends at 3, second starts at 4) and give maximum profit 50 + 70 = 120.
Example 2 — All Overlapping
$ Input: activities = [[1,4,30],[2,6,40],[5,8,20]]
Output: 40
💡 Note: Activities [1,4,30] and [2,6,40] overlap, [2,6,40] and [5,8,20] overlap. Best choice is single activity [2,6,40] with profit 40.
Example 3 — Chain of Activities
$ Input: activities = [[1,2,100],[3,4,200],[5,6,300]]
Output: 600
💡 Note: All three activities can be selected since none overlap: 1→2, 3→4, 5→6. Total profit = 100 + 200 + 300 = 600.

Constraints

  • 1 ≤ activities.length ≤ 104
  • activities[i].length == 3
  • 0 ≤ starti < endi ≤ 106
  • 1 ≤ profiti ≤ 104

Visualization

Tap to expand
INPUTALGORITHMRESULT[1,3,50][2,5,20][4,6,70][6,8,30]Activities with:Start time, End time, Profit1Sort by end time2Binary search for compatibility3DP: max(skip, include + best_before)4Build optimal solution120Maximum ProfitSelected: [1,3,50] + [4,6,70]50 + 70 = 120Key Insight:Sorting activities by end time enables efficient DP with binary search,transforming O(n²) compatibility checks into O(n log n) solution.TutorialsPoint - Weighted Activity Selection | DP + Binary Search
Asked in
Google 25 Amazon 20 Microsoft 18 Meta 15
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen