Skip to content
AI360Xpert
Beta
GeeksforGeeks: Hard2-D Dynamic Programming

Matrix Chain Multiplication

Official exercise: GeeksforGeeks

Problem in Plain English

Find the fewest scalar multiplications needed to multiply a chain of matrices described by a dimension array. Choose parentheses without changing matrix order.

Problem Statement

Given dimension array arr, matrix Mi has dimensions arr[i-1] × arr[i] for i = 1 through arr.length-1. Return the minimum scalar multiplication count over all parenthesizations. Multiplying an a × b matrix by a b × c matrix costs a × b × c scalar multiplications. You need the cost, not the product matrices or the parentheses.

Constraints

  • 2 <= arr.length <= 100.
  • 1 <= arr[i] <= 200.
  • Matrix order is fixed; only parentheses may change.

Examples

Example 1

Input
arr = [2,1,3,4]
Output
20

The split after M1 costs 1 × 3 × 4 + 2 × 1 × 4 = 20; the split after M2 costs 2 × 1 × 3 + 2 × 3 × 4 = 30.

Example 2

Input
arr = [3,4]
Output
0

There is one 3 × 4 matrix. No multiplication is performed.

Example 3

Input
arr = [1,2,3,4,3]
Output
30

Left-associated products cost 6, then 12, then 12 scalar operations, totaling 30, the minimum over all splits.

Intuition

The final multiplication divides any parenthesized chain into two contiguous chains. Their result dimensions depend only on the endpoints, so try every final split and reuse the cheapest subchains. For Example 1, multiplying the last two matrices first costs 12, then multiplying the first matrix by that result costs 8, totaling 20. Multiplying the first two first costs 6 plus 24, totaling 30. A locally cheap multiplication can therefore lead to a more expensive complete chain.

Approaches

Interval DP

Optimal

Solution Details

Reveal Interval DP: intuition, complexity, and code

Hints

Hint 1
Identify the last multiplication in a parenthesized chain.
Hint 2
Its split separates two contiguous subchains with fixed result dimensions.
Hint 3
Minimize over k and fill intervals by increasing length; a single matrix costs zero.

Edge Cases

  • Two dimensions describe one matrix and return zero, not the product of the dimensions.
  • Equal dimensions give equal costs for all parenthesizations, so no tie reconstruction is needed.
  • The maximum dimension array length requires all interval lengths through 99.

Common Mistakes and Interview Tips

  • Using arr[i] instead of arr[i-1] for the left row count changes the matrix dimensions.
  • Allowing k = j makes the right subchain empty and breaks the recurrence.
  • Filling i and j in an arbitrary order reads unfinished subchains.
  • Choosing the cheapest adjacent multiply greedily fails on Example 1.

Key Takeaway

When a final operation splits a fixed-order structure, define an interval state and enumerate that final split. Evaluate states in a dependency order and charge only the work done after the subproblems.