

The array ‘arr’ is sorted.
You are given ‘arr’ = [1, 2, 3] and ‘freq’ = [10, 30, 20], we can construct binary search trees such that

We can clearly see that the minimum cost of the tree is 90.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the size of the array.
The second line of each test case contains ‘N’ space-separated integers representing the element of the array, ‘arr’.
The third line of each test case contains ‘N’ space-separated integers representing the element of the array, ‘freq’.
For each test case print a single integer representing the minimum cost of the BST.
Print a separate line for each test case.
1 <= T <= 10
1 <= |arr| = |freq| <= 100
0 <= freq[i] <= 10^8
Time Limit = 1 sec
You do not need to print anything. It has already been taken care of. Just implement the given function.
In this approach, we will try to see that the minimum cost to form a BST from the subarray ‘arr[i: j]’ is equal to
Here r is considered as the root for the nodes ranging from i to r- 1 in left child and r + 1 to j in the right child of r.
We will create a recursive solution minCostSubarray( freq, i, j, level), ‘freq’ is the frequency array, i and j are the starting and ending indices of the subarray given and level is the depth of current subtree in the tree. This function returns the minimum cost of BST in subarray arr[i : j].
In this approach, we can see there are many overlapping subproblems, thus it can be solved by creating a cache and storing the solution for each subarray in the cache.
We will create a recursive solution minCostSubarray( freq, i, j, level, cache), ‘freq’ is the frequency array, i and j are the starting and ending indices of the subarray given and level is the depth of current subtree in the tree. ‘cache’ is the cache that stores the solution. This function returns the minimum cost of BST in subarray arr[i : j].
In this approach, we can see there are many overlapping subproblems, thus it can be solved by dynamic programming.
We use an auxiliary array cost[n][n] to store the solutions of subproblems. Here
Here to find the ‘sum(freq[i: j])’ We can make an optimization to store the prefix sum of ‘freq’ array. ‘freqSum’ and sum(freq[i: j]) = freqSum[j + 1] - freqSum[i]