Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of matrix chain multiplication

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?

like image 634
rgamber Avatar asked Jan 23 '12 18:01

rgamber


Video Answer


1 Answers

The final solution is to calculate m[0,N]. But all m[i,j] values need to be calculated before m[0,N] can be calculated. This makes it O(N^2).

From the recursion formula you can see each m[i,j] calculation needs O(N) complexity.

So O(N^3) for the complete solution.

like image 61
Rajendran T Avatar answered Oct 06 '22 23:10

Rajendran T