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-sum-of-non-adjacent-nodes/1
Maximum Non-Adjacent Nodes Sum
Difficulty: Medium Accuracy: 55.35%
Given the root of a binary tree with integer values. Your task is to select a subset of nodes such that the sum of their values is maximized, with the condition that no two selected nodes are directly connected that is, if a node is included in the subset, neither its parent nor its children can be included.
Examples:
Input: root = [11, 1, 2]
Output: 11
Explanation: The maximum sum is obtained by selecting the node 11.
Input: root = [1, 2, 3, 4, N, 5, 6]
Output: 16
Explanation: The maximum sum is obtained by selecting the nodes 1, 4, 5 and 6, which are not directly connected to each other. Their total sum is 16.
Constraints:
1 β€ number of nodes β€ 104
1 β€ node.data β€ 105
Solution:
class Solution:
def getMaxSum(self, root):
def helper(node):
if not node:
return (0, 0)
left = helper(node.left)
right = helper(node.right)
include = node.data + left[1] + right[1]
exclude = max(left) + max(right)
return (include, exclude)
return max(helper(root))
Top comments (0)