Problem solution · Python

Maximum Profit from Valid Topological Order in DAG

Maximum Profit from Valid Topological Order in DAG: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
30 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Maximum Profit from Valid Topological Order in DAG, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 30 lines of Python from the credited upstream file 3530.py.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Profit from Valid Topological Order in DAG · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def maxProfit(self, n: int, edges: list[list[int]], score: list[int]) -> int:    # need[i] := the bitmask representing all nodes that must be placed before    # node i    need = [0] * n    # dp[mask] := the maximum profit achievable by placing the set of nodes    # represented by `mask`    dp = [-1] * (1 << n)    dp[0] = 0     for u, v in edges:      need[v] |= 1 << u     # Iterate over all subsets of nodes (represented by bitmask `mask`)    for mask in range(1 << n):      if dp[mask] == -1:        continue      # Determine the position of the next node to be placed (1-based).      pos = mask.bit_count() + 1      # Try to place each node `i` that hasn't been placed yet.      for i in range(n):        if mask >> i & 1:          continue        # Check if all dependencies of node `i` are already placed.        if (mask & need[i]) == need[i]:          newMask = mask | 1 << i  # Mark node `i` as placed.          dp[newMask] = max(dp[newMask], dp[mask] + score[i] * pos)     return dp[-1] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗