All problems

Problem 158

Binary Tree Maximum Path Sum

Hard · 30 pts · Tree, Depth-First Search, Dynamic Programming

Problem

A path in a binary tree is a sequence of nodes where each pair of neighbours is connected by an edge and no node appears twice. A path has at least one node and does not have to pass through the root. Its sum is the total of its node values. Print the largest sum over all paths. Values can be negative. For every node, compute the best downward path starting at it: its value plus the better of its children's downward paths, ignoring a child if its path is negative. The best path that bends at this node is its value plus both children's (non-negative) downward paths; track the maximum of these.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).

Output

Print the maximum path sum.

Constraints

1 <= number of nodes <= 30000; -1000 <= value <= 1000

Example input

3
1 2 3

Example output

6

Explanation

In the tree with root 1 and children 2 and 3, the path 2 → 1 → 3 uses all three nodes and has sum 2 + 1 + 3 = 6, the largest possible.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Count Good Nodes in Binary Tree Next: Lowest Common Ancestor of a Binary Tree