> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/greedy-algorithms/13.-minimum-cost-tree-from-leaf-values.md).

# 13. 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
```

## Solution : (Dp + Memo)

**Trying to split at each possible point**

```cpp
class Solution
{
public:
    int findVal(vector<int> &arr, int start, int end, vector<vector<int>> &dp)
    {

        if (start >= end)
        {
            return 0;
        }

        if (dp[start][end] != -1)
        {
            return dp[start][end];
        }

        int ans = INT_MAX;

        for (int i = start; i < end; i++)
        {
            int left = findVal(arr, start, i, dp);
            int right = findVal(arr, i + 1, end, dp);

            int leftMax = 0;
            int rightMax = 0;

            for (int j = start; j <= i; j++)
            {
                leftMax = max(leftMax, arr[j]);
            }

            for (int j = i + 1; j <= end; j++)
            {
                rightMax = max(rightMax, arr[j]);
            }

            ans = min(ans, left + right + leftMax * rightMax);
        }

        dp[start][end] = ans;
        return ans;
    }

    int mctFromLeafValues(vector<int> &arr)
    {
        int n = arr.size();
        vector<vector<int>> dp(n, vector<int>(n, -1));

        return findVal(arr, 0, n - 1, dp);
    }
};
```

## Solution: (Greedy)

**Approach:**\
**Finding the minimum product and the smaller element is just a special case of finding a valley.**\
**Finding the valley point i.e minimum value and multiplying it.**\
**Remove it from the array as it is the minimum.**

```cpp
class Solution
{
public:
    int mctFromLeafValues(vector<int> &arr)
    {

        int sum = 0;
        while (arr.size() > 1)
        {

            for (int i = 0; i < arr.size(); i++)
            {
                if (i == 0 && arr[i] <= arr[i + 1])
                {
                    sum += arr[i] * arr[i + 1];
                    arr.erase(arr.begin() + i);
                }
                else if (i == arr.size() - 1 && arr[i] <= arr[i - 1])
                {
                    sum += arr[i] * arr[i - 1];
                    arr.erase(arr.begin() + i);
                }
                else
                {
                    if (arr[i] <= arr[i + 1] && arr[i] <= arr[i - 1])
                    {
                        sum += (arr[i + 1] < arr[i - 1]) ? arr[i] * arr[i + 1] : arr[i] * arr[i - 1];
                        arr.erase(arr.begin() + i);
                    }
                }
            }
        }

        return sum;
    }
};
```

**Time Complexity: O(n^2)**


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/greedy-algorithms/13.-minimum-cost-tree-from-leaf-values.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
