Input : N = 10 , edges = {{5,8}, {4,6}, {9,1}, {10,4}, {1,3}, {2,3}, {7,9}, {6,2}, {5,10}}
Output : 5
Explanation : One possible matching is {5-8 , 10-4, 1-3, 7-9 , 6-2}
Input : N = 10 , edges = {{6,3}, {2,8}, {1,8}, {4,10}, {7,3}, {8,7}, {1,5}, {5,9}, {10,9}}
Output : 4
Explanation : one possible matching is {6-3, 2-8, 4-10, 1-5}
We can solve this problem using Dynamic Programming (DP) with a 2D dp array to track maximum "pairs" achievable in subtrees. There are two conditions:
- Exclude current node: dp[0][u] stores the maximum pairs possible without including node u itself.
- Include current node: dp[1][u] stores the maximum pairs possible by including u in a matching with a child.
A Depth-First Search (DFS) calculates optimal values for dp at each node based on its children. Finally, the maximum number of pairs in a perfect matching is the maximum between dp[0][0] (excluding root) and dp[1][0] (including root).