Problem solution · C++

Maximum Profit from Valid Topological Order in DAG

Maximum Profit from Valid Topological Order in DAG: a C++ 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
40 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

  • 40 lines of C++ from the credited upstream file 3530.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 3 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 · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int maxProfit(int n, vector<vector<int>>& edges, vector<int>& score) {    const int maxMask = 1 << n;    // need[i] := the bitmask representing all nodes that must be placed before    // node i    vector<int> need(n);    // dp[mask] := the maximum profit achievable by placing the set of nodes    // represented by `mask`    vector<int> dp(maxMask, -1);    dp[0] = 0;     for (const vector<int>& edge : edges) {      const int u = edge[0];      const int v = edge[1];      need[v] |= 1 << u;    }     // Iterate over all subsets of nodes (represented by bitmask `mask`)    for (unsigned mask = 0; mask < maxMask; ++mask) {      if (dp[mask] == -1)        continue;      // Determine the position of the next node to be placed (1-based).      const int pos = popcount(mask) + 1;      // Try to place each node `i` that hasn't been placed yet.      for (int i = 0; i < n; ++i) {        if (mask >> i & 1)          continue;        // Check if all dependencies of node `i` are already placed.        if ((mask & need[i]) == need[i]) {          const int newMask = mask | 1 << i;  // Mark node `i` as placed.          dp[newMask] = max(dp[newMask], dp[mask] + score[i] * pos);        }      }    }     return dp.back();  }}; 

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 ↗