This is a solved problem in “Introduction to Algorithms”, by Cormen, et. al.
Ch. 15, Section 15.2: Matrix Chain Multiplication. Pg. 373.
The objective is to parenthesize the matrix chain product A1.A2.A3…..An such that there are minimum number of scalar multiplications.
For Ai.Ai+1….Ak.Ak+1…..Aj,
Matrix Ai has dimension pi-1xpi
The author comes up with the recursion
m[i,j] = 0 if i=j
= min {m[i,k] + m[k+1] + pi-1.pk.pj} where i goes from k to (j-1) if i<j
(m[i,j] is the minimum number of scalar multiplications required for the product Ai….Aj)
So far I understood, but then the time complexity he says is O(n^3).
When I look at the pseudo-code, there are 3 for loops, so its correct. But I don’t understand this intuitively by looking at the recursion.
Can anyone please help?
The final solution is to calculate
m[0,N]. But allm[i,j]values need to be calculated beforem[0,N]can be calculated. This makes itO(N^2).From the recursion formula you can see each
m[i,j]calculation needsO(N)complexity.So
O(N^3)for the complete solution.