Back to challenges
Hard 0 solved 0% acceptance

Matrix Chain Multiplication

Find the cheapest order to multiply a chain of matrices.

What you'll learn

  • Define DP over subchains
  • Try every split point
  • Minimize multiplication cost

Problem

Matrix i has size dimensions[i] × dimensions[i+1]. Multiplying a p×q matrix by a q×r matrix costs p·q·r scalar multiplications. Choose where to put parentheses so multiplying the whole chain costs the least.

Implement min_multiplications(dimensions).

Input

dimensions: n + 1 sizes describing n matrices.

Output

Return the minimum total cost.

Constraints

2 ≤ length of dimensions ≤ 200; 1 ≤ each size ≤ 500

Examples

Example 1
Input:
dimensions = [10, 30, 5, 60]

Expected output:
expected = 4500
Input:
std::vector<long long> dimensions = {10, 30, 5, 60};

Expected output:
long long expected = 4500;
Input:
long[] dimensions = new long[] {10, 30, 5, 60};

Expected output:
long expected = 4500;

Explanation

(A×B)×C costs 10·30·5 + 10·5·60 = 4500, cheaper than A×(B×C) = 27000.

Example 2
Input:
dimensions = [5, 10]

Expected output:
expected = 0
Input:
std::vector<long long> dimensions = {5, 10};

Expected output:
long long expected = 0;
Input:
long[] dimensions = new long[] {5, 10};

Expected output:
long expected = 0;

Explanation

A single matrix needs no multiplication: 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The order of multiplication changes the total cost even though the final matrix shape stays the same.

Hint 2

Try every possible split point for each interval and reuse smaller interval results.

Hint 3

Use the dimensions array carefully: each subproblem depends on the endpoints around the matrices, not the matrix count alone.

Expected complexity

O(n^3) time, O(n^2) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.