Leetcode 2467: Most Profitable Path in a Tree

grid47
grid47
Exploring patterns and algorithms
Mar 5, 2024 8 min read

In a tree with n nodes labeled from 0 to n - 1, each node has a gate with a price to open. Alice starts at node 0 and Bob starts at node bob. Alice moves towards a leaf node, and Bob moves towards node 0. At every node, both Alice and Bob either pay the price to open the gate, or they receive a reward. If they reach a node simultaneously, they share the price/reward equally. Return the maximum net income Alice can achieve if she travels towards the optimal leaf node.
Problem
Approach
Steps
Complexity
Input: You are given the tree as a 2D integer array edges, a starting position bob for Bob, and an array amount where amount[i] gives the cost or reward at node i. The value is negative for a cost and positive for a reward. Alice starts at node 0, and both Alice and Bob move towards their respective destinations in each second.
Example: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]
Constraints:
• 2 <= n <= 105
• edges.length == n - 1
• 0 <= ai, bi < n
• ai != bi
• edges represents a valid tree
• 1 <= bob < n
• amount[i] is an even integer in the range [-104, 104]
Output: Return the maximum net income Alice can have by traveling towards the optimal leaf node.
Example: For edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, and amount = [-2,4,2,-4,6], the output is 6.
Constraints:
• The answer is an integer.
Goal: The goal is to compute the maximum net income Alice can get while traveling towards the best leaf node.
Steps:
• Build an adjacency list to represent the tree.
• Use depth-first search (DFS) to determine the distances and parent nodes of all nodes in the tree.
• Simulate Bob's path towards node 0, updating the gates along his path.
• Simulate Alice's path towards the optimal leaf node, while considering Bob's path and any shared gates.
• Return the maximum net income Alice can achieve by following the optimal path.
Goal: The given input should represent a valid tree with the provided constraints.
Steps:
• The tree has between 2 and 100,000 nodes.
• The input edges form a valid undirected tree.
• The gates' costs and rewards are given as even integers in the specified range.
Assumptions:
• The tree is rooted at node 0, and the game proceeds in discrete steps.
Input: For edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, and amount = [-2,4,2,-4,6]
Explanation: Alice and Bob start at nodes 0 and 3, respectively. As they move, Alice and Bob both pay or receive rewards as they pass through nodes. The goal is to compute the maximum net income Alice can achieve. In this example, Alice’s optimal path is through nodes 0 -> 1 -> 3 -> 4, where her net income becomes 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus