Optimal Array Multiplication Sequence
InterviewTime limit1sMemory limit128 MB
Given the dimensions of a chain of matrices, find the minimum number of scalar multiplications needed to compute their product.
- Level
Medium4 of 10
- Topics
- Dynamic programming, Matrix, Array, Implementation
- Solved
- No attempts yet
Problem
Given two arrays and , we can determine the array using the standard definition of matrix multiplication:
For this product to be defined, the number of columns in must equal the number of rows in . Let and denote the number of rows and columns of , respectively. The result has the same number of rows as and the same number of columns as , and the number of scalar multiplications needed to compute all of is
For example, if is a array and is a array, it takes multiplications to compute .
To multiply more than two arrays we may choose how to proceed. For instance, the product can be computed as or as . Suppose is , is , and is . The two orders require different numbers of multiplications:
The order clearly affects how many multiplications are required. Given the size of each array in a sequence of arrays to be multiplied, determine the minimum possible number of scalar multiplications over all valid orders of computing the product.
Input
The input consists of several test cases. Each test case begins with an integer , the number of arrays to be multiplied, followed by pairs of integers giving the number of rows and columns of each array, in the same order in which the arrays are to be multiplied. is no larger than . A value of for indicates the end of the input. Adjacent arrays are always dimensioned so that their product is defined.
Output
For each test case, output on a single line the minimum number of scalar multiplications needed to compute the product of all the arrays. Prefix each line with the case number in the form Case X: , numbered sequentially starting from .