Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Printing Matrix Chain Multiplication (A Space Optimized Solution)
Next article icon

Python Program for Matrix Chain Multiplication | DP-8

Last Updated : 20 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:

    (ABC)D = (AB)(CD) = A(BCD) = ....

However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,

    (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations     A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.

Clearly, the first parenthesization requires less number of operations. Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.

  Input: p[] = {40, 20, 30, 10, 30}      Output: 26000     There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.   Let the input 4 matrices be A, B, C and D.  The minimum number of    multiplications are obtained by putting parenthesis in following way   (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30    Input: p[] = {10, 20, 30, 40, 30}    Output: 30000    There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30.    Let the input 4 matrices be A, B, C and D.  The minimum number of    multiplications are obtained by putting parenthesis in following way   ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30    Input: p[] = {10, 20, 30}     Output: 6000     There are only two matrices of dimensions 10x20 and 20x30. So there    is only one way to multiply the matrices, cost of which is 10*20*30
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Following is a recursive implementation that simply follows the above optimal substructure property. 

Python3
# A naive recursive implementation that # simply follows the above optimal  # substructure property  import sys  # Matrix A[i] has dimension p[i-1] x p[i] # for i = 1..n def MatrixChainOrder(p, i, j):      if i == j:         return 0      _min = sys.maxsize          # place parenthesis at different places      # between first and last matrix,      # recursively calculate count of     # multiplications for each parenthesis     # placement and return the minimum count     for k in range(i, j):              count = (MatrixChainOrder(p, i, k)               + MatrixChainOrder(p, k + 1, j)                    + p[i-1] * p[k] * p[j])          if count < _min:             _min = count;           # Return minimum count     return _min;   # Driver program to test above function arr = [1, 2, 3, 4, 3]; n = len(arr);  print("Minimum number of multiplications is ",                 MatrixChainOrder(arr, 1, n-1));  # This code is contributed by Aryan Garg 

Output
Minimum number of multiplications is  30

Time complexity: The time complexity of the algorithm is O(n^3) where n is the number of matrices in the chain. This is because we have three nested loops and each loop runs n times.

Space complexity: The space complexity of the algorithm is O(n^2) because we are using a two-dimensional array to store the intermediate results. The size of the array is n x n.

Dynamic Programming Solution 

Python
# Dynamic Programming Python implementation of Matrix # Chain Multiplication. See the Cormen book for details # of the following algorithm import sys  # Matrix Ai has dimension p[i-1] x p[i] for i = 1..n def MatrixChainOrder(p, n):     # For simplicity of the program, one extra row and one     # extra column are allocated in m[][].  0th row and 0th     # column of m[][] are not used     m = [[0 for x in range(n)] for x in range(n)]      # m[i, j] = Minimum number of scalar multiplications needed     # to compute the matrix A[i]A[i + 1]...A[j] = A[i..j] where     # dimension of A[i] is p[i-1] x p[i]      # cost is zero when multiplying one matrix.     for i in range(1, n):         m[i][i] = 0      # L is chain length.     for L in range(2, n):         for i in range(1, n-L + 1):             j = i + L-1             m[i][j] = sys.maxsize             for k in range(i, j):                  # q = cost / scalar multiplications                 q = m[i][k] + m[k + 1][j] + p[i-1]*p[k]*p[j]                 if q < m[i][j]:                     m[i][j] = q      return m[1][n-1]  # Driver program to test above function arr = [1, 2, 3, 4, 3] size = len(arr)  print("Minimum number of multiplications is " +        str(MatrixChainOrder(arr, size))) # This Code is contributed by Bhavya Jain 

Output
Minimum number of multiplications is 30

Please refer complete article on Matrix Chain Multiplication | DP-8 for more details!


Next Article
Printing Matrix Chain Multiplication (A Space Optimized Solution)

K

kartik
Improve
Article Tags :
  • Python
  • Python matrix-program
Practice Tags :
  • python

Similar Reads

    Matrix Chain Multiplication
    Given the dimension of a sequence of matrices in an array arr[], where the dimension of the ith matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. When two matrices of size m*
    15+ min read
    Matrix Chain Multiplication (A O(N^2) Solution)
    Given an array arr[] of size n, which represents the chain of matrices such that the ith matrix Ai is of dimension arr[i-1] x arr[i]. The task is to find the minimum number of multiplications needed to multiply the chain. Example:Input: arr[] = [40, 20, 30, 10, 30]Output: 26000 Explanation: There ar
    6 min read
    Printing brackets in Matrix Chain Multiplication Problem
    Given an array arr[] which represents the chain of matrices such that the dimensions of the ith matrix are arr[i-1] x arr[i]. The task is to find the correct parenthesis of the matrices such that when we multiply all the matrices together, the cost or total number of element multiplications is minim
    15+ min read
    Python Program for Matrix Chain Multiplication | DP-8
    Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices because matrix multiplic
    5 min read
    Printing Matrix Chain Multiplication (A Space Optimized Solution)
    Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We ha
    12 min read
    Minimum sum of multiplications of n numbers
    Given an integer array arr[] of length n. Your goal is to reduce the array to a single element by repeatedly applying the following operationSelect any two adjacent elements, call them x and y.Remove x and y from the array.Insert a new element equal to (x + y) mod 100 at their position.The cost of t
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences