AlgoFrames

Matrix chain multiplication

Standard · Write code · about 15 min

dims describes a chain of matrices: matrix i (counting from 1) is dims[i - 1] × dims[i]. Multiplying an a × b matrix by a b × c matrix costs a · b · c scalar multiplications.

Return the fewest scalar multiplications needed to multiply the whole chain. With fewer than two entries in dims there are no matrices; return 0.

Example 1

Input:

[[2,10,1,5]]

Output:

30

(A1 A2) A3 costs 20 + 10 = 30; A1 (A2 A3) costs 50 + 100 = 150.

Example 2

Input:

[[40,20,30,10,30]]

Output:

26000

(A1 (A2 A3)) A4.

Constraints

  • 1 ≤ dims.length ≤ 100
  • 1 ≤ dims[i] ≤ 100

Learn the idea first: Interval DP: matrix chain, burst balloons, palindrome partitioning, a visual lesson.

More Interval DP: matrix chain, burst balloons, palindrome partitioning problems