Loading...
Loading...
You are given a list of integer arrays matrices describing matrices that must be multiplied together in order. Each element in matrices contains [a, b] meaning a matrix with a rows and b columns. Consecutive matrices are compatible: matrices[i][1] == matrices[i + 1][0] for every valid i.
Multiplying an m by n matrix by an n by k matrix costs m * n * k scalar multiplications. You can multiply the matrices in any order as long as their relative order stays the same.
Return the minimum number of scalar multiplications needed to multiply all of the matrices into a single matrix. If matrices contains a single matrix, return 0.
Input: matrices = [[1, 2],
[2, 3],
[3, 4]]
Output: 18
Explanation: Multiplying the first two matrices costs `1 * 2 * 3 = 6` and gives a `1` by `3` matrix. Multiplying that result by the last matrix costs `1 * 3 * 4 = 12`, for a total of `18`.
Input: matrices = [[5, 10]]
Output: 0
Explanation: There is only one matrix, so no multiplications are needed and the cost is `0`.
Input: matrices = [[2, 2],
[2, 2]]
Output: 8
Explanation: The two `2` by `2` matrices are multiplied once, costing `2 * 2 * 2 = 8` scalar multiplications.
Input: matrices = [[ 1, 100],
[100, 1],
[ 1, 100],
[100, 1]]
Output: 201
Explanation: Multiplying the first two matrices costs `1 * 100 * 1 = 100` and multiplying the last two costs `1 * 100 * 1 = 100`. Multiplying the two resulting `1` by `1` matrices costs `1`, for a total of `201`.
matrices.length ≤100matrices[i][0] ≤100matrices[i][1] ≤100matrices[i][1] == matrices[i + 1][0] for 1≤i+1< matrices.length