Similar Problems
Similar Problems not available
Maximum Score Of A Node Sequence - Leetcode Solution
Companies:
LeetCode: Maximum Score Of A Node Sequence Leetcode Solution
Difficulty: Hard
Problem Statement:
You are given a binary tree with weights for each node. Each path in the tree starts at the root node and ends in any leaf node. The score of a path is the sum of the weights along the path.
You are also given an integer limit. Return the maximum score of any path such that the absolute difference between the weights of the path's start and end nodes is less than or equal to limit.
Solution:
To solve this problem, we'll use a recursive approach. Starting from the root node, we'll traverse through each node of the tree and compute the maximum score path that ends at that node. To do this, we'll recursively compute the maximum score paths of the left and right subtrees of the current node. We'll then check if adding the weight of the current node to either of these paths gives us a path with a higher score than any path we have seen before. If it does, we update our answer.
We'll also keep track of the minimum and maximum weights seen so far on the current path. This helps us compare the weight of the start and end nodes.
Here's the pseudo-code for the algorithm:
def maximumScore(root, limit):
max_score = float('-inf')
def dfs(node, max_weight, min_weight):
nonlocal max_score
if not node:
return
# Update current path's max and min weights
max_weight = max(max_weight, node.val)
min_weight = min(min_weight, node.val)
# Recursively compute scores for left and right subtrees
left_score = dfs(node.left, max_weight, min_weight)
right_score = dfs(node.right, max_weight, min_weight)
# Find the maximum score path that ends at this node
score = node.val
if left_score is not None:
score = max(score, node.val + left_score)
if right_score is not None:
score = max(score, node.val + right_score)
# Update answer if score is greater than any we have seen before
if (max_weight - min_weight) <= limit:
max_score = max(max_score, score)
# Return maximum score path that ends at this node
return score
# Call dfs for root node
dfs(root, root.val, root.val)
return max_score
Time Complexity:
The time complexity of the algorithm is O(N), where N is the number of nodes in the tree. This is because we visit each node once and perform constant time operations at each node.
Space Complexity:
The space complexity of the algorithm is O(H), where H is the height of the tree. This is because the maximum depth of the call stack in our recursive function is equal to the height of the tree.
Maximum Score Of A Node Sequence Solution Code
1