1715. Leaf Product Tree Cost

A robotics club lines up its robots in a fixed row, where arr[i] is the strength of the robot at position i. They run a merge ceremony that builds a binary tree whose leaves are the robots in exactly this left-to-right order, and every internal node has two children. Joining a left group with the right group next to it costs (the strongest robot in the left group) multiplied by (the strongest robot in the right group). Return the smallest possible total cost of all joins, as a 64-bit integer. There are 2 to 100000 robots with strengths from 1 to 10000. Aim for O(n) time and O(n) space: repeatedly removing the weakest robot at cost strength times the smaller of its neighbours is optimal, and a decreasing monotonic stack performs all those removals in one pass.

Example 1

Input:
arr = [3,5,2]
Output:
25
Explanation:

Joining (3,5) first costs 15 and then 5 * 2 = 10 for 25; joining (5,2) first costs 10 and then 3 * 5 = 15, also 25.

Example 2

Input:
arr = [4,4]
Output:
16
Explanation:

There is a single join between two groups of strength 4, costing 16.

Example 3

Input:
arr = [1,2,3,4]
Output:
20
Explanation:

Removing the weakest each time costs 1*2 + 2*3 + 3*4 = 20, which is the minimum.

Constraints

2 ≤ n ≤ 105

1 ≤ arr[i] ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…