-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy path059-min_cost.py
32 lines (26 loc) · 942 Bytes
/
059-min_cost.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import sys
class Matrix(object):
def __init__(self, first, second):
self.first = first
self.second = second
class MatrixMultiplicationCost(object):
def find_min_cost(self, matrices):
if matrices is None:
raise TypeError('matrices cannot be None')
if not matrices:
return 0
size = len(matrices)
T = [[0] * size for _ in range(size)]
for offset in range(1, size):
for i in range(size-offset):
j = i + offset
min_cost = sys.maxsize
for k in range(i, j):
cost = (T[i][k] + T[k+1][j] +
matrices[i].first *
matrices[k].second *
matrices[j].second)
if cost < min_cost:
min_cost = cost
T[i][j] = min_cost
return T[0][size-1]