Menu
CoddyTech

Matrix Chain Multiplication

A chain of matrices is described by dims: matrix i has dims[i] rows and dims[i+1] columns, so each matrix fits the next one. Multiplying a p × q matrix by a q × r matrix takes p × q × r scalar multiplications and gives a p × r matrix. Every way of placing the parentheses gives the same final product, but not at the same cost. Return the fewest scalar multiplications needed to multiply the whole chain.

Function

matrixChainOrder(dims: integer-array) → integer
dimsinteger-array
the sizes along the chain: matrix i is dims[i] × dims[i+1]
Returnsinteger
the fewest scalar multiplications that multiply the whole chain

Constraints

  • 2 ≤ dims.length ≤ 100, so the chain holds between 1 and 99 matrices.
  • 1 ≤ dims[i] ≤ 100
  • The answer is at most 98 × 106, well inside a 32-bit signed integer.

Examples

Input
dims = [4, 10, 3, 12]
Output
264
Explanation
Multiplying the first two costs 4 × 10 × 3 = 120 and leaves a 4 × 3 matrix, which times the 3 × 12 matrix adds 144: 264. The other order costs 360 + 480 = 840.
challenge icon

Follow-up

Can you also count how many different parenthesizations reach the minimum cost?

Reset code
def matrixChainOrder(dims):
    # Write code here

Test #1

Test #2

Test #3

Argument

dims = [4, 10, 3, 12]

Expected Output

264