Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! 💻🔥
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! 🚀
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/maximum-path-sum-from-any-node/1
Maximum path sum
Difficulty: Medium Accuracy: 42.92%
Given the root of a binary tree, your task is to find the maximum path sum. The path may start and end at any node in the tree.
Examples:
Input: root[] = [10, 2, 10, 20, 1, N, -25, N, N, N, N, 3, 4]
Output: 42
Explanation: Max path sum is represented using green colour nodes in the above binary tree.
Input: root[] = [-17, 11, 4, 20, -2, 10]
Output: 31
Explanation: Max path sum is represented using green colour nodes in the above binary tree.
Constraints:
1 ≤ number of nodes ≤ 103
-104 ≤ node->data ≤ 104
Solution:
class Solution:
def findMaxSum(self, root):
self.maxSum = float('-inf')
def dfs(node):
if not node:
return 0
left = max(0, dfs(node.left))
right = max(0, dfs(node.right))
self.maxSum = max(self.maxSum, left + right + node.data)
return node.data + max(left, right)
dfs(root)
return self.maxSum
Top comments (0)