# 1130. Minimum Cost Tree From Leaf Values

Given an array `arr` of positive integers, consider all binary trees such that:

* Each node has either 0 or 2 children;
* The values of `arr` correspond to the values of each **leaf** in an in-order traversal of the tree.  *(Recall that a node is a leaf if and only if it has 0 children.)*
* The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.

Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node.  It is guaranteed this sum fits into a 32-bit integer.

**Example 1:**

```
Input: arr = [6,2,4]
Output: 32
Explanation:
There are two possible trees.  The first has non-leaf node sum 36, and the second has non-leaf node sum 32.

    24            24
   /  \          /  \
  12   4        6    8
 /  \               / \
6    2             2   4
```

**Constraints:**

* `2 <= arr.length <= 40`
* `1 <= arr[i] <= 15`
* It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than `2^31`).

```cpp
// Monotonic Decreasing Stack
int mctFromLeafValues(vector<int>& arr) { // time: O(n); space: O(n)
    int res = 0, n = arr.size();
    vector<int> stack({INT_MAX});
    for (int a : arr) {
        while (stack.back() <= a) {
            int mid = stack.back();
            stack.pop_back();
            res += mid * min(a, stack.back());
        }
        stack.push_back(a);
    }
    for (int i = 2; i < stack.size(); ++i) {
        res += stack[i - 1] * stack[i];
    }
    return res;
}
```

```cpp
// Top-Down Dynamic Programming
// dp(left, right)= min( max(arr[left ... i]) * max(arr[i+1 ... right]) + dp(left, i) + dp(i + 1, right) ) 
// where i go from left to right-1
int dp(int left, int right, vector<vector<int> >& memo, vector<vector<int> >& maxi) {
    if (left == right) return 0; // leaf
    if (memo[left][right] != -1) return memo[left][right];
    int res = INT_MAX;
    for (int i = left; i < right; ++i) {
        res = min(res, maxi[left][i] * maxi[i + 1][right] + dp(left, i, memo, maxi) + dp(i + 1, right, memo, maxi));
    }
    return memo[left][right] = res;
}
int mctFromLeafValues(vector<int>& arr) { // time: O(n^3); space: O(n^2)
    int n = arr.size();
    // maxi[i][j]: records the maximal number in arr[i...j]
    vector<vector<int> > memo(n, vector<int>(n, -1)), maxi(n, vector<int>(n, 0));
    for(int i = 0; i < n; ++i){
        maxi[i][i] = arr[i];
        for (int j = i + 1; j < n; ++j) {
            maxi[i][j] = max(maxi[i][j - 1], arr[j]);
        }
    }
    return dp(0, arr.size() - 1, memo, maxi);
}
```

```cpp
// Bottom-Up Dynamic Programming
int mctFromLeafValues(vector<int>& arr) { // time: O(n^3); space: O(n^2)
    int n = arr.size();
    vector<vector<int> > dp(n, vector<int>(n)), maxi(n, vector<int>(n));
    for (int i = 0; i < n; ++i) {
        int local_max = 0;
        for (int j = i; j < n; ++j) {
            if (arr[j] > local_max) {
                local_max = arr[j];
            }
            maxi[i][j] = local_max;
        }
    }
    for (int len = 1; len < n; ++len) {
        for (int left = 0; left + len < n; ++left) {
            int right = left + len;
            dp[left][right] = INT_MAX;
            if (len == 1) {
                dp[left][right] = arr[left] * arr[right];
            } else {
                for (int k = left; k < right; ++k) {
                    dp[left][right] = min(dp[left][right], 
                                          dp[left][k] + dp[k + 1][right] + maxi[left][k] * maxi[k + 1][right]);
                }
            }
        }
    }
    return dp[0][n - 1];
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/stack/1130.-minimum-cost-tree-from-leaf-values.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
