Matrix-chain combine two halves
Updated
dims a[0..n]: matrix k is a[k]×a[k+1]. dp[i][j] = min cost to multiply matrices i..j. Split at k: dp[i][k]+dp[k+1][j] + a[i]*a[k+1]*a[j+1]. Two halves, then one multiply of the results.
What to focus on
A chain of two matrices has one split. Three matrices have two parenthesizations. Fill by chain length. The min walks every legal k.
Worked examples
two matrices one split
a = [1, 4, 9]- A 1×4, B 4×9
- cost 1*4*9=36
- only k=0
Result: 36
three matrices
a = [1, 4, 9, 1]- (AB)C = 36+9=45
- A(BC) = 36+4=40
- min 40
Result: 40
singleton chain
a = [1, 4, 9], i = 0, j = 0- one matrix, no multiply
Result: 0
Try it
Write matrixChain(a). a is dim numbers. dp[i][j] is min cost to multiply matrices i..j. Name both parenthesizations. Return the min cost. A singleton chain costs 0. [1, 4, 9] → 36. [1, 4, 9, 1] → min(45, 40)=40. i=0, j=0 on [1, 4, 9] → 0.
Dims are positive integers. The chain has 1, 2, or 3 matrices. A singleton is in scope because it is a matrix-chain base.