A graphics pipeline multiplies a chain of matrices M1 · M2 · … · Mn. Matrix multiplication is associative, so any bracketing gives the same result, but not the same amount of work: multiplying a p × q matrix by a q × r matrix takes p · q · r scalar multiplications.
The sizes are given as an array dims of length n + 1: matrix Mi (counting from 1) has dims[i - 1] rows and dims[i] columns.
minMultiplications(dims) returns the fewest scalar multiplications needed to compute the whole product. A single matrix needs 0.
bestBracketing(dims) returns that bracketing as a string. A single matrix is written M1, M2, …, and a product of two parts X and Y is written (X x Y), with one space on each side of the x.
Rules:
When several split points give the same lowest cost for a sub-chain, split after the earliest matrix. This makes the bracketing unique.
If dims is not an array of at least two positive safe integers, throw a TypeError.
Chains can have 300 matrices with sizes up to 1,000. The number of bracketings grows exponentially, so trying them all will not finish.
minMultiplications([10, 30, 5, 60]); // 4500bestBracketing([10, 30, 5, 60]); // "((M1 x M2) x M3)": 1500 + 3000, not 9000 + 18000bestBracketing([40, 20, 30, 10, 30]); // "((M1 x (M2 x M3)) x M4)", cost 26000bestBracketing([2, 2, 2, 2]); // "(M1 x (M2 x M3))": both bracketings cost 16, split earliestminMultiplications([7, 3]); // 0
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
5
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.