# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def max_gain(node):
nonlocal max_sum
if not node:return 0
left_max = max(max_gain(node.left), 0)
right_max = max(max_gain(node.right),0)
new_price = node.val + left_max + right_max
max_sum = max(max_sum, new_price)
return node.val + max(left_max, right_max)
max_sum = float('-inf')
max_gain(root)
return max_sum