
You are given ‘stones’ = [4, 3, 4, 2, 5] and ‘K’ = 3, Here one way you can first merge [3, 4, 2] with a cost of 9, to form the array [4, 9, 5] then merge these piles as [18], with a cost of 18. The total cost to merge the array is 27, which is the minimum of all the possible ways. Hence the answer is 27.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains two space-separated integers ‘N’ and ‘K’, representing the number of piles and ‘K’ the integer given.
The second line of each test case contains ‘N’ space-separated integers, representing the elements of the array ‘stones’.
For each test case print a single integer representing the minimum cost to merge the whole array into 1.
Print a separate line for each test case.
1 <= T <= 10
1 <= |N| <= 10^2
2 <= K <= N
1 <= |stones| <= 10^5
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 look at all possible subarrays of the array, for any array, we will have to add the sum of its elements to the solution at one point or another. If the subarray has only ‘K’ elements we will return the sum of all elements otherwise we will further check if more piles can be formed in the subarray or not and return the minimum of all possible solutions.
Since for each subarray, we will require the sum of its element we will create a prefix sum array to get the subarray sum in O(1) time.
We will create a recursive function mergeStonesRecur(stones, preArr, k , start, end), where start and end are the starting and ending indices of the current subarray, while preArr is the prefix sum array of stones.
In this approach, we will store the value of each recursive call in the previous approach, and try to reuse it. We will create a cache and check if the values are already stored in the cache or not.
We will create a recursive function mergeStonesRecur(stones, preArr, k , start, end, cache), where start and end are the starting and ending indices of the current subarray, while preArr is the prefix sum array of stones. Cache is the cache of all the unique recursive calls.
In this approach, we will build the solution from the bottom up.
We store the solution of subarray stones[i: j] in dp[i][j] as
dp[i][j] = min(dp[i][k] + dp[k + 1][j]) + sum of elements in the subarray
This approach is very similar to the last approach.