Maximum Profit from Valid Topological Order in DAG Problem
Description
LeetCode Problem 3530.
You are given a Directed Acyclic Graph (DAG) with n nodes labeled from 0 to n - 1, represented by a 2D array edges, where edges[i] = [u_i, v_i] indicates a directed edge from node u_i to v_i. Each node has an associated score given in an array score, where score[i] represents the score of node i.
You must process the nodes in a valid topological order. Each node is assigned a 1-based position in the processing order.
The profit is calculated by summing up the product of each node's score and its position in the ordering.
Return the maximum possible profit achievable with an optimal topological order.
A topological order of a DAG is a linear ordering of its nodes such that for every directed edge u → v, node u comes before v in the ordering.
Example 1:
Input: n = 2, edges = [[0,1]], score = [2,3]
Output: 8
Explanation:

Node 1 depends on node 0, so a valid order is [0, 1].
Node Processing Order Score Multiplier Profit Calculation
0 1st 2 1 2 × 1 = 2
1 2nd 3 2 3 × 2 = 6
The maximum total profit achievable over all valid topological orders is 2 + 6 = 8.
Example 2:
Input: n = 3, edges = [[0,1],[0,2]], score = [1,6,3]
Output: 25
Explanation:

Nodes 1 and 2 depend on node 0, so the most optimal valid order is [0, 2, 1].
Node Processing Order Score Multiplier Profit Calculation
0 1st 1 1 1 × 1 = 1
2 2nd 3 2 3 × 2 = 6
1 3rd 6 3 6 × 3 = 18
The maximum total profit achievable over all valid topological orders is 1 + 6 + 18 = 25.
Constraints:
1 <= n == score.length <= 221 <= score[i] <= 10^50 <= edges.length <= n * (n - 1) / 2edges[i] == [u_i, v_i]denotes a directed edge fromu_itov_i.0 <= u_i, v_i < nu_i != v_i- The input graph is guaranteed to be a DAG.
- There are no duplicate edges.
Solution
Approach: Bitmask DP
Since n <= 22, a bitmask can represent the set of nodes already placed. Let f[mask] be the best profit after placing exactly the nodes in mask in a valid order. For each node v not in mask whose prerequisites (all u with an edge u -> v) are all in mask, place it next at position popcount(mask) + 1: f[mask | v] = max(f[mask | v], f[mask] + score[v] * position). The answer is f of the full set.
Complexity: O(2^n * n) time and O(2^n) extra space, where n is the number of nodes.
class Solution:
def maxProfit(self, n: int, edges: List[List[int]], score: List[int]) -> int:
pre = [0] * n
for u, v in edges:
pre[v] |= 1 << u
full = (1 << n) - 1
f = [-1] * (full + 1)
f[0] = 0
for mask in range(full):
cur = f[mask]
if cur < 0:
continue
pos = bin(mask).count("1") + 1
for v in range(n):
if not (mask >> v) & 1 and (pre[v] & mask) == pre[v]:
nm = mask | (1 << v)
val = cur + score[v] * pos
if val > f[nm]:
f[nm] = val
return f[full]