Matrix Chain Multiplication (DP) : Just Short Of Optimal 
Difficulty: Hard

Given a sequence of __N__ matrices A[i], i=1 to N+1, multiply them so that the product of the matrices, in order, is unambiguous and needs __Just Short of Optimal__ number of scalar multiplication.

__Just Short of Optimal__ is defined as the __second most optimal__ number of scalar multiplications.

It is assured that matrix dimensions allow multiplication, in order.

__Note:__ In the case where there are two equally optimal answers, any one of them is to be given as output.


Input Format:
First line contains an integer __T__

First line of each test case contains a single integer __N__ .

The next line contains __N+1__ space separated integers denoting the dimensions of matrices in the order specified above.

__Contraints:__

1<= T <=10

3<= N <= 150

1<= Dimensions of Matrices  <= 60



Output Format:
For each test case, print a single integer denoting the __Just Short of Optimal__ number of scalar multiplications involved for the given matrices.

Sample Input:
1

3

10 30 5 60


Sample Output:
27000

Python 3 starter code:


Reference solution (C++):

	#include <iostream>
	#include<limits.h>
	#include<vector>
	#include<algorithm>
	using namespace std;
	int main() 
	{
	int t,n,i,j,k,L;
	cin>>t;
	while(t--)
	{
		cin>>n;
		int a[n+1];
		for(i=0;i<=n;i++)
		{
			cin>>a[i];
		}
		int m[n+1][n+1];
		for(i=1;i<=n;i++)
		m[i][i]=0;
		for (L=2; L<n; L++)   
    	{
        	for (i=1; i<=n-L+1; i++)
        	{
            	j = i+L-1;
            	m[i][j] = INT_MAX;
            	for (k=i; k<=j-1; k++)
            	{
                	int q = m[i][k] + m[k+1][j] + a[i-1]*a[k]*a[j];
                	if (q < m[i][j])
                    m[i][j] = q;
            	}
        	}
    	}
    	vector<int>v;
    	for(k=1;k<n;k++)
    	v.push_back(m[1][k] + m[k+1][n] + a[0]*a[k]*a[n]);
    	sort(v.begin(),v.end());
    	m[1][n-1]=v[0];
    	if(v.size()>1)
    	m[1][n-1]=v[1];
    	cout<<m[1][n-1]<<endl;
	}
	return 0;
}