Taro Logo

Difference Between Maximum and Minimum Price Sum

Hard
Asked by:
Media.net
Directi
0 views
Topics:
TreesRecursionDynamic ProgrammingGraphs

There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.

The price sum of a given path is the sum of the prices of all nodes lying on that path.

The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root.

Return the maximum possible cost amongst all possible root choices.

Example 1:

Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]
Output: 24
Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.
- The second path contains the node [2] with the price [7].
The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.

Example 2:

Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1]
Output: 2
Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.
- The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.
- The second path contains node [0] with a price [1].
The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • 0 <= ai, bi <= n - 1
  • edges represents a valid tree.
  • price.length == n
  • 1 <= price[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can node prices contain negative integers, or are they strictly positive?
  2. How is a "path" defined in this context? Can a valid path consist of just a single node, or does it require at least two nodes (an edge)?
  3. Is the tree guaranteed to be connected, and what should be returned if the tree is empty or contains only a single node?
  4. Can multiple nodes have the exact same price value, and how should paths with identical sums be handled?
  5. Could the maximum possible price sum exceed standard 32-bit integer limits, requiring 64-bit integers (long long in C++, long in Java)?uss

Brute Force Solution

Approach

The problem asks for the maximum difference between the maximum and minimum price path starting from any chosen root. For any chosen root, the minimum path sum is always just the root node's price, so the task simplifies to finding the maximum path sum starting from the root to some leaf node, minus the leaf node's price. This can be viewed as finding a path from the root to a leaf where one endpoint excludes its price, which can be solved efficiently using a two-pass tree rerooting dynamic programming approach.

Here's how the algorithm would work step-by-step:

  1. Handle the edge case where the tree consists of only one node by immediately returning zero.
  2. Build the tree's adjacency list and perform a bottom-up depth-first search to calculate two values for each subtree: the maximum path sum including leaves, and the maximum path sum excluding the end leaf.
  3. Perform a top-down rerooting depth-first search that tracks path values coming from the parent direction.
  4. At each node, combine the best incoming full paths and paths without leaves to determine the maximum valid path cost when treating that node as the root.
  5. Pass the updated contributions to each child to reroot the tree in linear time.
  6. Return the maximum difference found across all possible root candidates.

Code Implementation

def max_output(n: int, edges: list[list[int]], price: list[int]) -> int:
    if n == 1:
        return 0

    # Build the adjacency list for the tree representation.
    adjacency = [[] for _ in range(n)]
    for node_u, node_v in edges:
        adjacency[node_u].append(node_v)
        adjacency[node_v].append(node_u)

    # Compute max path sum with and without leaf for subtrees.
    subtree_full = [0] * n
    subtree_without_leaf = [0] * n

    def dfs_bottom_up(current_node: int, parent_node: int) -> None:
        current_price = price[current_node]
        max_child_full = 0
        max_child_without = 0
        is_leaf = True
        for neighbor in adjacency[current_node]:
            if neighbor != parent_node:
                is_leaf = False
                dfs_bottom_up(neighbor, current_node)
                if subtree_full[neighbor] > max_child_full:
                    max_child_full = subtree_full[neighbor]
                if subtree_without_leaf[neighbor] > max_child_without:
                    max_child_without = subtree_without_leaf[neighbor]
        subtree_full[current_node] = current_price + max_child_full
        if is_leaf:
            subtree_without_leaf[current_node] = 0
        else:
            subtree_without_leaf[current_node] = current_price + max_child_without

    import sys
    sys.setrecursionlimit(200000)
    dfs_bottom_up(0, -1)

    max_difference = 0

    # Reroot to compute the answer for every node as root.
    def dfs_reroot(current_node: int, parent_node: int, parent_full: int, parent_without: int) -> None:
        nonlocal max_difference
        best_paths_full = [(parent_full, parent_node)]
        best_paths_without = [(parent_without, parent_node)]
        for neighbor in adjacency[current_node]:
            if neighbor != parent_node:
                best_paths_full.append((subtree_full[neighbor], neighbor))
                best_paths_without.append((subtree_without_leaf[neighbor], neighbor))
        best_paths_full.sort(reverse=True)
        best_paths_without.sort(reverse=True)

        cost_for_node = 0
        for full_val, full_neighbor in best_paths_full[:2]:
            for without_val, without_neighbor in best_paths_without[:2]:
                if full_neighbor != without_neighbor:
                    candidate = full_val
                    if candidate > cost_for_node:
                        cost_for_node = candidate
        if cost_for_node > max_difference:
            max_difference = cost_for_node

        for neighbor in adjacency[current_node]:
            if neighbor != parent_node:
                chosen_full = best_paths_full[1][0] if best_paths_full[0][1] == neighbor else best_paths_full[0][0]
                chosen_without = best_paths_without[1][0] if best_paths_without[0][1] == neighbor else best_paths_without[0][0]
                next_parent_full = price[current_node] + chosen_full
                next_parent_without = price[current_node] + chosen_without
                dfs_reroot(neighbor, current_node, next_parent_full, next_parent_without)

    dfs_reroot(0, -1, 0, 0)
    return max_difference

Big(O) Analysis

Time Complexity
O(n) – Each node and edge in the tree is visited a constant number of times during the two depth-first search traversals, keeping the overall time linear with respect to the number of nodes.
Space Complexity
O(n) – The adjacency list, subtree dynamic programming arrays, and the recursion call stack each require O(n) memory.

Optimal Solution

Approach

The problem asks for the maximum difference between the maximum path sum and the minimum path sum starting at some root node. Because all prices are positive, the minimum path sum starting at any root is simply the price of the root node itself, and the maximum path sum must end at a leaf node. Therefore, the problem reduces to finding the maximum path sum between a root and a leaf, minus the price of the root, which is equivalent to finding a path between two nodes where one endpoint is excluded.

Here's how the algorithm would work step-by-step:

  1. Check if the tree consists of only one node, returning zero immediately since the difference is zero.
  2. Construct an undirected adjacency list from the given edges to represent the tree.
  3. Define a depth-first search function that returns two values for each subtree: the maximum path sum to a leaf including all nodes, and the maximum path sum where one leaf node's price is excluded.
  4. At each node, update the maximum difference by combining the best paths from different child subtrees, ensuring exactly one endpoint's price is excluded.
  5. Update and return the running maximum path sums for the current node up to its parent.
  6. Invoke the search starting from an arbitrary root and return the computed maximum cost.

Code Implementation

def max_price_sum(n: int, edges: list[list[int]], price: list[int]) -> int:
    if n == 1:
        return 0
    import sys
    sys.setrecursionlimit(200000)
    # Build the adjacency list for the undirected tree
    adjacency = [[] for _ in range(n)]
    for node_u, node_v in edges:
        adjacency[node_u].append(node_v)
        adjacency[node_v].append(node_u)
    max_cost = 0
    # Helper DFS to compute the maximum path sum with and without a leaf endpoint
    def dfs(current_node: int, parent_node: int) -> tuple[int, int]:
        nonlocal max_cost
        sum_with_leaf = price[current_node]
        sum_without_leaf = 0
        for neighbor in adjacency[current_node]:
            if neighbor == parent_node:
                continue
            child_with_leaf, child_without_leaf = dfs(neighbor, current_node)
            # Update the global maximum cost by combining paths through the current node
            max_cost = max(max_cost, sum_with_leaf + child_without_leaf, sum_without_leaf + child_with_leaf)
            sum_with_leaf = max(sum_with_leaf, price[current_node] + child_with_leaf)
            sum_without_leaf = max(sum_without_leaf, price[current_node] + child_without_leaf)
        return sum_with_leaf, sum_without_leaf
    # Run tree traversal from an arbitrary root
    dfs(0, -1)
    return max_cost

Big(O) Analysis

Time Complexity
O(n) – Every node and edge in the tree is visited a constant number of times during the depth-first search traversal.
Space Complexity
O(n) – The adjacency list and the recursion call stack each require memory proportional to the number of nodes n.

Edge Cases

Single node tree with no edges
How to Handle:
The algorithm should return 0 since the maximum and minimum path sums are both equal to the single node's price.
Tree with negative node prices
How to Handle:
A DFS-based path-finding approach naturally handles negative numbers by choosing not to extend a path when the accumulated sum decreases.
Extremely skewed linear tree resembling a linked list
How to Handle:
Recursion depth can equal the number of nodes, requiring iterative approaches or language-specific stack limit increases to prevent stack overflow.
Very large integers leading to sum overflow
How to Handle:
The solution must use 64-bit integers to accumulate path sums and prevent arithmetic overflow during calculations.
All node prices are identical
How to Handle:
The algorithm must correctly compute overlapping paths and return a difference of zero when all possible path sums are equal.
Graph with no valid nodes or edges provided
How to Handle:
Input validation should immediately check for empty structures and return zero or throw an appropriate argument exception.
Zero or mixed positive and negative pricing distributions
How to Handle:
Using Kadane-style tree DP ensures that we properly track both maximum and minimum path sums across zero crossings.