Example 1
- Input
- arr = [2,1,3,4]
- Output
- 20
The split after M1 costs 1 × 3 × 4 + 2 × 1 × 4 = 20; the split after M2 costs 2 × 1 × 3 + 2 × 3 × 4 = 30.
Find the fewest scalar multiplications needed to multiply a chain of matrices described by a dimension array. Choose parentheses without changing matrix order.
Given dimension array arr, matrix Mi has dimensions arr[i-1] × arr[i] for i = 1 through arr.length-1. Return the minimum scalar multiplication count over all parenthesizations. Multiplying an a × b matrix by a b × c matrix costs a × b × c scalar multiplications. You need the cost, not the product matrices or the parentheses.
2 <= arr.length <= 100.1 <= arr[i] <= 200.The split after M1 costs 1 × 3 × 4 + 2 × 1 × 4 = 20; the split after M2 costs 2 × 1 × 3 + 2 × 3 × 4 = 30.
There is one 3 × 4 matrix. No multiplication is performed.
Left-associated products cost 6, then 12, then 12 scalar operations, totaling 30, the minimum over all splits.
The final multiplication divides any parenthesized chain into two contiguous chains. Their result dimensions depend only on the endpoints, so try every final split and reuse the cheapest subchains. For Example 1, multiplying the last two matrices first costs 12, then multiplying the first matrix by that result costs 8, totaling 20. Multiplying the first two first costs 6 plus 24, totaling 30. A locally cheap multiplication can therefore lead to a more expensive complete chain.
Reveal Interval DP: intuition, complexity, and code
arr[i] instead of arr[i-1] for the left row count changes the matrix dimensions.When a final operation splits a fixed-order structure, define an interval state and enumerate that final split. Evaluate states in a dependency order and charge only the work done after the subproblems.