All problems

Problem 608

Maximum Product of Splitted Binary Tree

Medium · 20 pts · Tree, Depth-First Search

Problem

Remove exactly one edge of a binary tree, splitting it into two trees. Maximise the product of the sums of the two trees, and print that maximum product modulo 1000000007. Take the remainder only after finding the maximum. Compute the total sum S, then every subtree sum s gives the product s × (S - s). The product can exceed 2^53, so compare the products using 64-bit or big integers.

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 product modulo 1000000007.

Constraints

2 <= number of nodes <= 50000; 1 <= value <= 10000

Example input

6
1 2 3 4 5 6

Example output

110

Explanation

The tree 1 2 3 4 5 6 has total sum 21. Cutting the edge above node 2 separates a subtree of sum 2 + 4 + 5 = 11 from the rest (sum 10), for a product of 110, which is the maximum.

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

Previous: Lowest Common Ancestor of Deepest Leaves Next: Longest Univalue Path