Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Maximum sum path in a Matrix
Next article icon

Maximum path sum in matrix

Last Updated : 29 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a matrix of size n * m. Find the maximum path sum in the matrix. The maximum path is the sum of all elements from the first row to the last row where you are allowed to move only down or diagonally to left or right. You can start from any element in the first row.

Examples: 

Input: mat[][] = 10 10 2 0 20 4
1 0 0 30 2 5
0 10 4 0 2 0
1 0 2 20 0 4
Output: 74
Explanation: The maximum sum path is 20-30-4-20.

Input: mat[][] = 1 2 3
9 8 7
4 5 6
Output: 17
Explanation: The maximum sum path is 3-8-6.

Approach:

The idea is to use dynamic programming to calculate the maximum path sum in a matrix. Starting from the first row, for each cell in the matrix, we update its value by adding the maximum of the possible moves from the previous row (up, left, right). This way, we propagate the maximum possible sum at each step. Finally, we find the maximum value in the last row and return it as the result.

Below is the implementation of the above approach:

C++
// Approach: Dynamic Programming // Language: C++  #include <bits/stdc++.h> using namespace std;  // Function to find the maximum path sum int maximumPath(vector<vector<int>>& mat) {     int n = mat.size(), m = mat[0].size();          // Initialize result with the maximum value in the first row     int res = *max_element(mat[0].begin(), mat[0].end());          // Traverse the matrix row by row     for (int i = 1; i < n; i++) {         for (int j = 0; j < m; j++) {             // Get max value from possible previous row positions             int up = mat[i - 1][j];             int left = (j > 0) ? mat[i - 1][j - 1] : 0;             int right = (j < m - 1) ? mat[i - 1][j + 1] : 0;                          // Update current cell with max path sum             mat[i][j] += max({up, left, right});                          // Update result if current cell has a greater value             res = max(res, mat[i][j]);         }     }     return res; }  int main() {        // Input matrix     vector<vector<int>> mat = {{10, 10,  2,  0, 20,  4},                                 { 1,  0,  0, 30,  2,  5},                                 { 0, 10,  4,  0,  2,  0},                                 { 1,  0,  2, 20,  0,  4}};          // Output the maximum path sum     cout << maximumPath(mat) << endl;     return 0; } 
Java
// Approach: Dynamic Programming // Language: Java import java.util.*;  class GfG {     // Function to find the maximum path sum     public static int maximumPath(int[][] mat) {         int n = mat.length, m = mat[0].length;                  // Initialize result with the maximum value in the first row         int res = Arrays.stream(mat[0]).max().getAsInt();                  // Traverse the matrix row by row         for (int i = 1; i < n; i++) {             for (int j = 0; j < m; j++) {                 // Get max value from possible previous row positions                 int up = mat[i - 1][j];                 int left = (j > 0) ? mat[i - 1][j - 1] : 0;                 int right = (j < m - 1) ? mat[i - 1][j + 1] : 0;                                  // Update current cell with max path sum                 mat[i][j] += Math.max(up, Math.max(left, right));                                  // Update result if current cell has a greater value                 res = Math.max(res, mat[i][j]);             }         }         return res;     }      public static void main(String[] args) {                // Input matrix         int[][] mat = {             {10, 10,  2,  0, 20,  4},             { 1,  0,  0, 30,  2,  5},             { 0, 10,  4,  0,  2,  0},             { 1,  0,  2, 20,  0,  4}         };                  // Output the maximum path sum         System.out.println(maximumPath(mat));     } } 
Python
# Approach: Dynamic Programming # Language: Python  def maximum_path(mat):     n = len(mat)     m = len(mat[0])          # Initialize result with the maximum value in the first row     res = max(mat[0])          # Traverse the matrix row by row     for i in range(1, n):         for j in range(m):             # Get max value from possible previous row positions             up = mat[i - 1][j]             left = mat[i - 1][j - 1] if j > 0 else 0             right = mat[i - 1][j + 1] if j < m - 1 else 0                          # Update current cell with max path sum             mat[i][j] += max(up, left, right)                          # Update result if current cell has a greater value             res = max(res, mat[i][j])          return res  # Input matrix mat = [     [10, 10, 2, 0, 20, 4],     [1, 0, 0, 30, 2, 5],     [0, 10, 4, 0, 2, 0],     [1, 0, 2, 20, 0, 4] ]  # Output the maximum path sum print(maximum_path(mat)) 
C#
// Approach: Dynamic Programming // Language: C# using System; using System.Linq;  class GfG {        // Function to find the maximum path sum     static int MaximumPath(int[,] mat) {         int n = mat.GetLength(0), m = mat.GetLength(1);                  // Initialize result with the maximum value in the first row         int res = mat.Cast<int>().Take(m).Max();                  // Traverse the matrix row by row         for (int i = 1; i < n; i++) {             for (int j = 0; j < m; j++) {                 // Get max value from possible previous row positions                 int up = mat[i - 1, j];                 int left = (j > 0) ? mat[i - 1, j - 1] : 0;                 int right = (j < m - 1) ? mat[i - 1, j + 1] : 0;                                  // Update current cell with max path sum                 mat[i, j] += Math.Max(Math.Max(up, left), right);                                  // Update result if current cell has a greater value                 res = Math.Max(res, mat[i, j]);             }         }         return res;     }      static void Main() {                // Input matrix         int[,] mat = {             {10, 10, 2, 0, 20, 4},             {1, 0, 0, 30, 2, 5},             {0, 10, 4, 0, 2, 0},             {1, 0, 2, 20, 0, 4}         };                  // Output the maximum path sum         Console.WriteLine(MaximumPath(mat));     } } 
JavaScript
// Approach: Dynamic Programming // Language: JavaScript  function maximumPath(mat) {     let n = mat.length, m = mat[0].length;          // Initialize result with the maximum value in the first row     let res = Math.max(...mat[0]);          // Traverse the matrix row by row     for (let i = 1; i < n; i++) {         for (let j = 0; j < m; j++) {             // Get max value from possible previous row positions             let up = mat[i - 1][j];             let left = (j > 0) ? mat[i - 1][j - 1] : 0;             let right = (j < m - 1) ? mat[i - 1][j + 1] : 0;                          // Update current cell with max path sum             mat[i][j] += Math.max(up, left, right);                          // Update result if current cell has a greater value             res = Math.max(res, mat[i][j]);         }     }     return res; }  // Input matrix let mat = [     [10, 10, 2, 0, 20, 4],     [1, 0, 0, 30, 2, 5],     [0, 10, 4, 0, 2, 0],     [1, 0, 2, 20, 0, 4] ];  // Output the maximum path sum console.log(maximumPath(mat)); 

Output
74

Time Complexity: O(n * m), where n is the number of rows and m is the number of columns, as we traverse the matrix once.
Auxiliary Space: O(1), since the matrix is updated in-place without using extra space.



Next Article
Maximum sum path in a Matrix
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Matrix
Practice Tags :
  • Matrix

Similar Reads

  • Maximum sum path in a Matrix
    Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum
    15+ min read
  • Pair with maximum sum in a Matrix
    Given a NxM matrix with N rows and M columns of positive integers. The task is to find the sum of pair with maximum sum in the matrix. Examples: Input : mat[N][M] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output : 41 Pair (25, 16) has the maximum sum Input : mat[N][M] = {{1,
    7 min read
  • Maximum XOR value in matrix
    Given a square matrix (N X N), the task is to find the maximum XOR value of a complete row or a complete column. Examples : Input : N = 3 mat[3][3] = {{1, 0, 4}, {3, 7, 2}, {5, 9, 10} }; Output : 14 We get this maximum XOR value by doing XOR of elements in second column 0 ^ 7 ^ 9 = 14 Input : N = 4
    7 min read
  • Find the maximum sum path in the given Matrix
    Consider an infinite matrix. The cells of the matrix are filled with natural numbers from the cell (1, 1) in the direction of top right to bottom left diagonally. Then the task is to output the Maximum path sum between two points (X1, Y1) and (X2, Y2). Matrix filling process is as follows: Examples:
    7 min read
  • Maximum Path sum in a N-ary Tree
    Given an undirected tree with n nodes numbered from 1 to n and an array arr[] where arr[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[][]. The task is to find the maximum path sum between any two nodes. (Both the nodes ca
    7 min read
  • Maximum sum path in a matrix from top to bottom
    Consider a n*n matrix. Suppose each cell in the matrix has a value assigned. We can go from each cell in row i to a diagonally higher cell in row i+1 only [i.e from cell(i, j) to cell(i+1, j-1) and cell(i+1, j+1) only]. Find the path from the top row to the bottom row following the aforementioned co
    15 min read
  • Find row with maximum sum in a Matrix
    Given an N*N matrix. The task is to find the index of a row with the maximum sum. That is the row whose sum of elements is maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Row 3 has max sum 35 Input :
    11 min read
  • Maximum sum rectangle in a 2D matrix | DP-27
    Given a 2D array, the task is to find the maximum sum sub-matrix in it. Example: Input: mat=[[1,2,-1,-4,-20],[-8,-3,4,2,1],[3,8,10,1,3],[-4,-1,1,7,-6]]Output: 29Explanation: The matrix is as follows and the green rectangle denotes the maximum sum rectangle which is equal to 29. This problem is mainl
    15+ min read
  • Maximum path sum in a triangle.
    We have given numbers in form of a triangle, by starting at the top of the triangle and moving to adjacent numbers on the row below, find the maximum total from top to bottom. Examples : Input : 3 7 4 2 4 6 8 5 9 3 Output : 23 Explanation : 3 + 7 + 4 + 9 = 23 Input : 8 -4 4 2 2 6 1 1 1 1 Output : 19
    15+ min read
  • Maximum decimal value path in a binary matrix
    Given binary square matrix [n*n]. Find maximum integer value in a path from top left to bottom right. We compute integer value using bits of traversed path. We start at index [0,0] and end at index [n-1][n-1]. from index [i, j], we can move [i, j+1] or [i+1, j]. Examples: Input : mat[][] = {{1, 1, 0
    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