leetcode 1130 - Minimum Cost Tree From Leaf Values

https://leetcode.com/problems/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.

1
2
3
4
5
    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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
int mctFromLeafValues(vector<int>& arr) {
int size = arr.size();
vector<vector<int>> memo(size, vector<int>(size, -1));

return mctFromLeafValues(arr, 0, arr.size() - 1, memo);
}

int mctFromLeafValues(vector<int>& arr, int i, int j,
vector<vector<int>> &memo) {
if (i == j) return 0;

if (memo[i][j] != -1) return memo[i][j];

int min_sum = INT_MAX;

for (int k = i; k < j; k++) {
set<int> s1, s2;

for (int m = i; m <= k; m++)
s1.insert(arr[m]);
for (int m = k + 1; m <= j; m++)
s2.insert(arr[m]);

min_sum = min(min_sum, (*prev(s1.end())) * (*prev(s2.end())) +
mctFromLeafValues(arr, i, k, memo) + mctFromLeafValues(arr, k+1, j, memo));
}

memo[i][j] = min_sum;

return min_sum;
}
};