\(\(\(
\)\(MinMatrixChain[r__]\  := \ 
      Module[{l, i, j, m, k, q, n}, 
n\  = \ 
          Length[r] - 1; 
m\  = \ 
          Table[0, {i, 1, n}, {j, 1, n}]; 
kl\  = \ 
          m; 
Do[
\(Do[
j\  = \ i\  + \ l\  - \ 1; 
m[\([i, j]\)]\  = \ 
                Infinity; 
Do[
q\  = \ 
                  m[\([i, k]\)]\  + \ m[\([k + 1, j]\)]\  + \ 
                    r[\([i]\)]\ r[\([k + 1]\)]\ r[\([j + 
                            1]\)]; 
If[
                  q\  < \ m[\([i, j]\)], \ m[\([i, j]\)]\  = \ q; \ 
                  kl[\([i, j]\)]\  = \ k;], 
{k, i, 
                  j - 1}], 
{i, 1, n - l + 1}];\) (*\ 
            Print[" l = ", l, \ " : ", \ MatrixForm[m]]; \ 
            Print["kl = ", \ kl]; \ 
            Print["---------"]*) , 
{l, 2, 
            n}]; 
Return[{m, 
            kl}];
]\)\)\)

r1  =  {40, 50, 20, 70, 20, 90, 80, 40, 90, 30, 20, 30, 
        10} 
{a1, k1}  =  MinMatrixChain[r1];
MatrixForm[a1]
MatrixForm[k1]

r2  =  {40, 50, 20, 70, 20, 90, 80}; 
{a2, k2}  =  MinMatrixChain[r2];
MatrixForm[a2]
MatrixForm[k2]

\(\(\(MaxMatrixChain[
        r__]\)\(\ \)\(:=\)\(\ \)\(Module[{l, i, j, m, k, q, 
          n}, 
n\  = \ 
          Length[r] - 1; 
m\  = \ 
          Table[0, {i, 1, n}, {j, 1, n}]; 
kl\  = \ 
          m; 
Do[
\(Do[
j\  = \ i\  + \ l\  - \ 1; 
m[\([i, j]\)]\  = \ 
                0; 
Do[
q\  = \ 
                  m[\([i, k]\)]\  + \ m[\([k + 1, j]\)]\  + \ 
                    r[\([i]\)]\ r[\([k + 1]\)]\ r[\([j + 
                            1]\)]; 
If[
                  q\  > \ m[\([i, j]\)], \ m[\([i, j]\)]\  = \ q; \ 
                  kl[\([i, j]\)]\  = \ k;], 
{k, i, 
                  j - 1}], 
{i, 1, n - l + 1}];\) (*\ 
            Print[" l = ", l, \ " : ", \ MatrixForm[m]]; \ 
            Print["kl = ", \ kl]; \ 
            Print["---------"]*) , 
{l, 2, 
            n}]; 
Return[{m, 
            kl}];
]\)\(
\)\)\)

r1  =  {40, 50, 20, 70, 20, 90, 80, 40, 90, 30, 20, 30, 
        10} 
{a1, k1}  =  MaxMatrixChain[r1];
MatrixForm[a1]
MatrixForm[k1]

r2  =  {40, 50, 20, 70, 20, 90, 
          80}; 
{a2, k2}  =  MaxMatrixChain[r2];
MatrixForm[a2]
MatrixForm[k2]