Matrix chain multiplication

Pattern: Partition and interval DP

hard

Matrix i is d[i] × d[i+1]. dp[i][j] is the cheapest way to multiply matrices i..j-1; try every split k for the last multiplication, which costs d[i] × d[k] × d[j].

The problem

Given d where matrix i has size d[i] × d[i+1], return the fewest scalar multiplications needed to multiply the whole chain.

Think first

  • What does the last multiplication combine?
  • What does it cost?
  • Which segments must be ready first?

Hints

    Brute force, and why it fails

    Try every bracketing: Catalan-many.

    The key insight

    Each bracketing has a last split, and the two sides are independent smaller problems.

    Dry run

    d = [2, 1, 3, 4]: matrices 2×1, 1×3, 3×4.

    Step 1 of 2

    The plan

    for length: for i, j = i + length: dp[i][j] = min over k of dp[i][k] + dp[k][j] + d[i] d[k] d[j]
    

    Complexity

    Time
    O(n³)
    Space
    O(n²)

    n² segments, n splits each.

    Edge cases

    • One matrix: 0.
    • Two matrices: one product.
    • Large dimensions.
    I've built my logic, show the code

    Java

    class Solution {
        public int matrixMultiplication(int[] d) {  // matrix i is d[i] x d[i + 1]
            int n = d.length;
            int[][] dp = new int[n][n];             // dp[i][j]: the cheapest way to multiply matrices i .. j - 1
            for (int len = 2; len < n; len++)
                for (int i = 0; i + len < n; i++) {
                    int j = i + len;
                    dp[i][j] = Integer.MAX_VALUE;
                    for (int k = i + 1; k < j; k++)     // the last multiplication splits the chain at k
                        dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j] + d[i] * d[k] * d[j]);
                }
            return dp[0][n - 1];
        }
    }

    C++

    class Solution {
    public:
        int matrixMultiplication(vector<int>& d) { // matrix i is d[i] x d[i + 1]
            int n = static_cast<int>(d.size());
            vector<vector<int>> dp(n, vector<int>(n, 0));   // the cheapest way to multiply matrices i .. j - 1
            for (int len = 2; len < n; len++)
                for (int i = 0; i + len < n; i++) {
                    int j = i + len;
                    dp[i][j] = INT_MAX;
                    for (int k = i + 1; k < j; k++)     // the last multiplication splits the chain at k
                        dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + d[i] * d[k] * d[j]);
                }
            return dp[0][n - 1];
        }
    };

    Python

    class Solution:
        def matrixMultiplication(self, d: list[int]) -> int:   # matrix i is d[i] x d[i + 1]
            n = len(d)
            dp = [[0] * n for _ in range(n)]        # dp[i][j]: the cheapest way to multiply matrices i .. j - 1
            for length in range(2, n):
                for i in range(n - length):
                    j = i + length
                    dp[i][j] = min(dp[i][k] + dp[k][j] + d[i] * d[k] * d[j] for k in range(i + 1, j))   # last split at k
            return dp[0][n - 1]

    Common mistakes

    • Off-by-one between matrices and d.
    • Filling by i instead of length.

    Similar problems