Given an array arr of positive integers, consider all binary trees such that:
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.)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 <= 401 <= arr[i] <= 152^31).Minimum Cost Tree From Leaf Values - LeetCode
Using DP (TC : O(n^3) , SC : O(n^2))
class Solution {
public:
int mctFromLeafValues(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> dp(n,vector<int>(n,0));
vector<vector<int>> max_table(n,vector<int>(n));//stores the max(nums[i]....nums[j])
for(int gap=0;gap<n;gap++)
{
for(int i=0,j=gap;j<n;i++,j++)
{
if(gap==0)
max_table[i][j] = nums[i];
else if(gap==1)
max_table[i][j] = max(nums[i],nums[j]);
else
max_table[i][j] = max({max_table[i+1][j-1],nums[i],nums[j]});
}
}
for(int gap=0;gap<n;gap++)
{
for(int i=0,j=gap;j<n;i++,j++)
{
if(gap==0)
dp[i][j] = 0;
else if(gap==1)
dp[i][j] = nums[i]*nums[j];
else
{
dp[i][j] = INT_MAX;
for(int k=i;k<j;k++)
{
dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]+max_table[i][k]*max_table[k+1][j]);
}
}
}
}
return dp[0][n-1];
}
};
Using Greedy (TC : O(n^2) , SC : O(1))