Matrix chain multiplication

Choose where to place the parentheses in a chain of matrix multiplications to minimise the total number of scalar multiplications.

Time O(n³)Space O(n²)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Dimensions p describe n matrices, where matrix i is p[i-1] by p[i]. dp[i, j] is the cheapest cost of multiplying matrices i through j. Trying every split point k between i and j, the cost is the cost of the left group plus the right group plus one multiplication of the two resulting matrices together.

Code

public static int MatrixChainOrder(int[] p) {
    int n = p.Length - 1;
    var dp = new int[n + 1, n + 1];
    for (int len = 2; len <= n; len++) {
        for (int i = 1; i <= n - len + 1; i++) {
            int j = i + len - 1;
            dp[i, j] = int.MaxValue;
            for (int k = i; k < j; k++) {
                int cost = dp[i, k] + dp[k + 1, j] + p[i - 1] * p[k] * p[j];
                if (cost < dp[i, j]) dp[i, j] = cost;
            }
        }
    }
    return dp[1, n];
}
static int matrixChainOrder(int[] p) {
    int n = p.length - 1;
    int[][] dp = new int[n + 1][n + 1];
    for (int len = 2; len <= n; len++) {
        for (int i = 1; i <= n - len + 1; i++) {
            int j = i + len - 1;
            dp[i][j] = Integer.MAX_VALUE;
            for (int k = i; k < j; k++) {
                int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
                if (cost < dp[i][j]) dp[i][j] = cost;
            }
        }
    }
    return dp[1][n];
}
int matrixChainOrder(const vector<int>& p) {
    int n = (int)p.size() - 1;
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
    for (int len = 2; len <= n; len++) {
        for (int i = 1; i <= n - len + 1; i++) {
            int j = i + len - 1;
            dp[i][j] = INT_MAX;
            for (int k = i; k < j; k++) {
                int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
                if (cost < dp[i][j]) dp[i][j] = cost;
            }
        }
    }
    return dp[1][n];
}
def matrix_chain_order(p: list[int]) -> int:
    n = len(p) - 1
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    for length in range(2, n + 1):
        for i in range(1, n - length + 2):
            j = i + length - 1
            dp[i][j] = float('inf')
            for k in range(i, j):
                cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j]
                if cost < dp[i][j]: dp[i][j] = cost
    return dp[1][n]

Tips

In the .NET library

Matrix multiplication is associative but not commutative, so only the grouping changes, never the order of the matrices. Picking a bad grouping on a long chain can cost orders of magnitude more multiplications than the best one.