


You are given an array 'ARR' consisting of 'N' positive integers, and you need to reduce the size of the array to 1 by performing an operation several number of times. In a single operation, you can merge any two adjacent elements of the array, and the cost of merging will be equal to the sum of those two elements. Find the minimum cost of reducing the given array by performing this operation several number of times.
In a single merge operation, the two elements are removed, and their sum is inserted at its place, hence decreasing the size of the array by 1 after each operation. For eg: Consider the array A1, A2, Ai-2, Ai-1, Ai, Aj, Aj+1, Aj+2 ,,,, An. Let the operation be performed on two indices i and j, So after merging the array will look like A1, A2, Ai-2, Ai-1, Ai+Aj, Aj+1, Aj+2,,,, An.
Note:
Note that the given operation will be performed only 'N'-1 times, where 'N' is the size of the given array.
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains the integer N, denoting the size of the sorted array.
The second line of each test case contains N space-separated integers denoting the array elements.
Output Format:
The only line of output of each test case should contain a single integer which denotes the minimum cost of merging the whole array.
1 <= T <= 50
1 <= N <= 100
1 <= ARR[i] <= 10^6
Time Limit: 1 sec
1
3
1 3 7
15
The optimal way of merging is as follows:
Merge (1, 3). The array becomes {4, 7}. Cost for this operation is 4.
Merge (4, 7). The array becomes {11}. Cost for this operation is 11.
Therefore the total cost of merging is 4 + 11 = 15.
1
4
3 2 4 1
20
The optimal way of merging is as follows:
1. Merge (3, 2), then array becomes {5, 4, 1}. Cost for this operation is 5.
2. Merge (4, 1), then array becomes {5, 5}. Cost for this operation is 5.
3. Merge (5, 5), then array becomes {10}. Cost for this operation is 10.
Therefore the total cost of merging is 5 + 5 + 10 = 20.
Don’t try greedy.
‘DP[L][R]’ = S('L', ‘R’) + min('DP[L][L]' + ‘DP[L + 1][R]’, ‘DP[L][L + 1]’ + ‘DP[L + 2][R]’, …, ‘DP[L][R – 1]’ + ‘DP[R][R]’)
O(N^3), where N is the size of the array.
Iterate a loop ‘k', for ‘i*j’ depth so ‘i’ and ‘j’ can be ‘N’ is worst-case so our all-time will be ‘N*N*N = N^3’.
O(N^2), where N is the size of the array.
Storing data in 2-d ‘DP’ matrix.