Matrix-Chain-Order(p)

1
n = length(p) - 1

2
for i = 1 to n

3
m[i,i] = 0
; Chains of length 1

4
for ws = 2 to n

5
for i = 1 to n - (ws - 1)

6
j = i + (ws - 1)

7
m[i,j] =

8
for k = i to j-1

9
q = m[i,k] + m[k+1, j] + P[i-1]P[k]P[j]

10
if q < m[i,j]

11
then m[i,j] = q

12
s[i,j] = k

13
return m and s

This algorithm requires
time and
memory.