place parenthesis at different places between first and last matrix , recursively calculate count of multiplications for each parenthesis placement and return the minimum count
for ( $ k = $ i ; $ k < $ j ; $ k ++ ) { $ count = MatrixChainOrder ( $ p , $ i , $ k ) + MatrixChainOrder ( $ p , $ k + 1 , $ j ) + $ p [ $ i - 1 ] * $ p [ $ k ] * $ p [ $ j ] ; if ( $ count < $ min ) $ min = $ count ; }