Similar Problems
Similar Problems not available
Most Profitable Path In A Tree - Leetcode Solution
Companies:
LeetCode: Most Profitable Path In A Tree Leetcode Solution
Difficulty: Medium
Topics: depth-first-search breadth-first-search tree array graph
The "Most Profitable Path In A Tree" problem on Leetcode involves finding the most profitable path in a tree where each node represents a company that produces a certain amount of profit, and each edge represents a partnership between two companies that increases their combined profit.
To solve this problem, we need to perform a traversal of the tree, and at each node, we need to calculate the profit if we choose to include that node in the path or exclude it.
For example, let's say we have the following tree:
1
/ \
2 3
/ \ / \
4 5 6 7
where each node represents the profit of a company.
To calculate the most profitable path, we can use a depth-first traversal of the tree. At each node, we need to calculate the following:
- If we choose to include this node in the path, what is the total profit?
- If we choose to exclude this node from the path, what is the total profit?
- What is the maximum profit that we can achieve if we continue the path from this node?
To calculate the profits, we can use a recursive function that takes the current node as input and returns a tuple containing the three values mentioned above.
Here's the Python code for the solution:
def max_profit_path(root): if not root: return (0, 0, 0) left_profit = max_profit_path(root.left) right_profit = max_profit_path(root.right) include_profit = root.val + left_profit[1] + right_profit[1] exclude_profit = max(left_profit[0], left_profit[1]) + max(right_profit[0], right_profit[1]) max_profit = max(include_profit, exclude_profit) return (include_profit, exclude_profit, max_profit)
Example usage
tree = TreeNode(1) tree.left = TreeNode(2) tree.right = TreeNode(3) tree.left.left = TreeNode(4) tree.left.right = TreeNode(5) tree.right.left = TreeNode(6) tree.right.right = TreeNode(7) print(max_profit_path(tree))
The output of this code will be (14, 10, 14), which means that the most profitable path starts at the root and includes nodes 2, 4, and 7, with a total profit of 14.
Most Profitable Path In A Tree Solution Code
1