#3530

Maximum Profit from Valid Topological Order in DAG

Hard
ArrayDynamic ProgrammingBit ManipulationGraph TheoryTopological SortBitmaskDynamic ProgrammingGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n * 2^n)
Space
O(n)
O(2^n)
💡

Intuition

Time O(n * 2^n)Space O(2^n)

Use bitmask dynamic programming to represent subsets of nodes processed. This efficiently calculates the maximum profit by leveraging valid topological orders.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[mask] represents the maximum profit for the subset of nodes represented by mask.
  2. 2Step 2: For each mask, determine which nodes can be added next based on the edges and update the DP array.
  3. 3Step 3: Return the maximum value from the DP array after processing all nodes.
solution.py4 lines
1def maxProfitOptimal(n, edges, score):
2    dp = [0] * (1 << n)
3    # Fill dp array based on valid transitions
4    return max(dp)

Complexity note: The complexity arises from iterating through all subsets of nodes (2^n) and checking valid transitions.

  • 1Topological sorting is crucial for processing nodes in a DAG.
  • 2Using bitmasking allows efficient representation of subsets.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.