Skip to content
Discussion options

You must be logged in to vote

We need to handle a tree structure where the decision to buy at a node affects its children's costs. This is a tree DP problem with knapsack-like constraints.

Approach:

  1. Tree Representation: Build an adjacency list to represent the company hierarchy as a tree.

  2. Dynamic Programming States: For each node u, compute two DP arrays:

    • dp0[u][c]: Maximum profit in u's subtree when parent did NOT buy, using budget c
    • dp1[u][c]: Maximum profit in u's subtree when parent DID buy, using budget c
  3. Recursive DFS Calculation:

    • Leaf Nodes: Base case where we consider buying at full or half price (if parent bought)
    • Internal Nodes:
      • Merge children's DP arrays using knapsack combination
      • Consider both bu…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Dec 16, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants