Matrix Chain Multiplication - Problem

Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.

We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:

  • (ABC)D = (AB)(CD) = A(BCD) = ...

However, the order in which we parenthesize the product affects the number of simple scalar multiplications needed to compute the product, or the efficiency. For example, suppose A is a 10×30 matrix, B is a 30×5 matrix, and C is a 5×60 matrix. Then:

  • (AB)C = (10×30×5) + (10×5×60) = 1,500 + 3,000 = 4,500 multiplications
  • A(BC) = (30×5×60) + (10×30×60) = 9,000 + 18,000 = 27,000 multiplications

Given an array dimensions which represents the dimensions of each matrix where dimensions[i] is the number of rows of matrix i and dimensions[i+1] is the number of columns of matrix i, return the minimum number of scalar multiplications needed to multiply all the matrices.

Input & Output

Example 1 — Basic Chain
$ Input: dimensions = [1,2,3,4]
Output: 18
💡 Note: Matrices are 1×2, 2×3, 3×4. Optimal: ((1×2) × (2×3)) × (3×4) = 6 + 12 = 18 operations
Example 2 — Two Matrices
$ Input: dimensions = [10,20,30]
Output: 6000
💡 Note: Only one way to multiply: 10×20×30 = 6000 operations
Example 3 — Larger Chain
$ Input: dimensions = [1,2,3,4,5]
Output: 38
💡 Note: Four matrices: 1×2, 2×3, 3×4, 4×5. Optimal parenthesization gives 38 operations

Constraints

  • 2 ≤ dimensions.length ≤ 200
  • 1 ≤ dimensions[i] ≤ 1000

Visualization

Tap to expand
INPUTdimensions = [1,2,3,4]1×22×33×4MatrixThree matrices to multiplyin optimal orderALGORITHM1Build DP table2Fill by chain length3Try all split points4Take minimum costDP Table[0][1]: 6[1][2]: 12[0][2]: 18RESULTMinimum Cost:18Optimal parenthesization:((A × B) × C)Cost breakdown:A×B: 1×2×3 = 6(AB)×C: 1×3×4 = 12Total: 6 + 12 = 18Key Insight:Dynamic programming breaks the problem into overlapping subproblems.By solving smaller chains first, we avoid exponential recalculation andachieve O(n³) time complexity instead of O(2ⁿ).TutorialsPoint - Matrix Chain Multiplication | Bottom-Up Dynamic Programming
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen