All problems

Problem 411

House Robber III

Medium · 20 pts · Tree, Dynamic Programming, Depth-First Search

Problem

The houses in a neighbourhood form a binary tree, and each node's value is the money in that house. A thief cannot rob two houses that are directly connected, meaning a house and its parent cannot both be robbed. Find the maximum amount the thief can steal. For each node compute two numbers, the best total if the node is robbed and the best total if it is not, and combine them from the leaves upwards.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print the maximum amount of money.

Constraints

1 <= number of nodes <= 10000; 0 <= value <= 10000

Example input

7
3 2 3 null 3 null 1

Example output

7

Explanation

In the tree 3 / 2 3 / _ 3 _ 1, robbing the root 3 and the two grandchildren 3 and 1 gives 7, and no other choice of unconnected houses gives more.

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

Previous: Deepest Leaves Sum Next: Distribute Coins in a Binary Tree