From 3cec92da1c79dcd6e2dadeb388fc8d77e58be2d7 Mon Sep 17 00:00:00 2001 From: Darsh Kantaria <91107260+darshkantaria@users.noreply.github.com> Date: Sun, 27 Oct 2024 14:17:56 +0530 Subject: [PATCH] Create Matrix Chain Multiplication --- .../Matrix Chain Multiplication" | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 "Beginner Level \360\237\223\201/Matrix Chain Multiplication" diff --git "a/Beginner Level \360\237\223\201/Matrix Chain Multiplication" "b/Beginner Level \360\237\223\201/Matrix Chain Multiplication" new file mode 100644 index 00000000..43367605 --- /dev/null +++ "b/Beginner Level \360\237\223\201/Matrix Chain Multiplication" @@ -0,0 +1,28 @@ +# Matrix Chain Multiplication + +Given an array `p` where `p[i]` represents the dimensions of the matrix \(A_i\) such that \(A_i\) has dimensions \(p[i-1] \times p[i]\) (for \(i \geq 1\)), find the minimum number of scalar multiplications needed to compute the product of a chain of matrices \(A_1 \times A_2 \times \ldots \times A_n\). + +The goal is to determine the most efficient order of multiplying these matrices. Matrix multiplication is associative, meaning the order of multiplication can be changed to reduce the number of scalar multiplications. However, matrices can only be multiplied if the number of columns in one matrix equals the number of rows in the next. + +For example, given the array `p = [10, 20, 30, 40, 30]`, matrices \(A_1\), \(A_2\), \(A_3\), and \(A_4\) would have dimensions \(10 \times 20\), \(20 \times 30\), \(30 \times 40\), and \(40 \times 30\), respectively. The goal is to find the minimum cost to compute \(A_1 \times A_2 \times A_3 \times A_4\). + +## Input +- An integer array `p` of size \( n+1 \), where \( n \) is the number of matrices. + +## Output +- An integer representing the minimum number of scalar multiplications needed to multiply the chain of matrices. + +### Constraints: +- \( 1 \leq n \leq 100 \) +- \( 1 \leq p[i] \leq 500 \) + +## Example + +**Input:** +p = [10, 20, 30, 40, 30] + +**Output:** +30000 + +**Explanation:** +The optimal order of multiplication is \(( (A_1 \times A_2) \times (A_3 \times A_4) )\), with a minimum cost of 30000 scalar multiplications.