Function for matrix chain multiplication
function matrixChainMemoised ( p , i , j ) { if ( i == j ) { return 0 ; } if ( dp [ i ] [ j ] != - 1 ) { return dp [ i ] [ j ] ; } dp [ i ] [ j ] = Number . MAX_VALUE ; for ( let k = i ; k < j ; k ++ ) { dp [ i ] [ j ] = Math . min ( dp [ i ] [ j ] , matrixChainMemoised ( p , i , k ) + matrixChainMemoised ( p , k + 1 , j ) + p [ i - 1 ] * p [ k ] * p [ j ] ) ; } return dp [ i ] [ j ] ; } function MatrixChainOrder ( p , n ) { let i = 1 , j = n - 1 ; return matrixChainMemoised ( p , i , j ) ; }