Open In App

Maximum sum path in a matrix from top to bottom

Improve
Improve
Like Article
Like
Save
Share
Report

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 condition such that the maximum sum is obtained.

Examples:  

Input : mat[][] = { {5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
Output : 28
{5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
The highlighted numbers from top to bottom
gives the required maximum sum path.
(7 + 8 + 11 + 2) = 28

Method 1: The idea is to find maximum sum or all paths starting with every cell of first row and finally return maximum of all values in first row. We use Dynamic Programming as results of many subproblems are needed again and again.

Implementation:

C++




// C++ implementation to find the maximum sum
// path in a matrix
#include <bits/stdc++.h>
using namespace std;
 
#define SIZE 10
 
// function to find the maximum sum
// path in a matrix
int maxSum(int mat[SIZE][SIZE], int n)
{
    // if there is a single element only
    if (n == 1)
        return mat[0][0];
 
    // dp[][] matrix to store the results
    // of each iteration
    int dp[n][n];
    int maxSum = INT_MIN, max;
 
    // base case, copying elements of
    // last row
    for (int j = 0; j < n; j++)
        dp[n - 1][j] = mat[n - 1][j];
 
    // building up the dp[][] matrix from
    // bottom to the top row
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j < n; j++) {
            max = INT_MIN;
 
            // finding the maximum diagonal element in the
            // (i+1)th row if that cell exists
            if (((j - 1) >= 0) && (max < dp[i + 1][j - 1]))
                max = dp[i + 1][j - 1];
            if (((j + 1) < n) && (max < dp[i + 1][j + 1]))
                max = dp[i + 1][j + 1];
 
            // adding that 'max' element to the
            // mat[i][j] element
            dp[i][j] = mat[i][j] + max;
        }
    }
 
    // finding the maximum value from the
    // first row of dp[][]
    for (int j = 0; j < n; j++)
        if (maxSum < dp[0][j])
            maxSum = dp[0][j];
 
    // required maximum sum
    return maxSum;
}
 
// Driver program to test above
int main()
{
    int mat[SIZE][SIZE] = { { 5, 6, 1, 7 },
                            { -2, 10, 8, -1 },
                            { 3, -7, -9, 11 },
                            { 12, -4, 2, 6 } };
    int n = 4;
 
    cout << "Maximum Sum = "
         << maxSum(mat, n);
 
    return 0;
}


Java




// Java implementation to find the
// maximum sum path in a matrix
import java.io.*;
 
class MaxSumPath {
//int mat[][];
 
// function to find the maximum
// sum path in a matrix
static int maxSum(int[][] mat, int n)
{
    // if there is a single element only
    if (n == 1)
        return mat[0][0];
 
    // dp[][] matrix to store the results
    // of each iteration
    int dp[][] = new int[n][n];
    int maxSum = Integer.MIN_VALUE, max;
 
    // base case, copying elements of
    // last row
    for (int j = 0; j < n; j++)
        dp[n - 1][j] = mat[n - 1][j];
 
    // building up the dp[][] matrix
    // from bottom to the top row
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j < n; j++) {
            max = Integer.MIN_VALUE;
 
            // finding the maximum diagonal
            // element in the (i+1)th row
            // if that cell exists
            if (((j - 1) >= 0) &&
                 (max < dp[i + 1][j - 1]))
                 max = dp[i + 1][j - 1];
            if (((j + 1) < n) &&
                (max < dp[i + 1][j + 1]))
                max = dp[i + 1][j + 1];
 
            // adding that 'max' element
            // to the mat[i][j] element
            dp[i][j] = mat[i][j] + max;
        }
    }
 
    // finding the maximum value from
    // the first row of dp[][]
    for (int j = 0; j < n; j++)
        if (maxSum < dp[0][j])
            maxSum = dp[0][j];
 
    // required maximum sum
    return maxSum;
}
 
    // Driver code
    public static void main (String[] args) {
     
    int mat[][] = { { 5, 6, 1, 7 },
                    { -2, 10, 8, -1 },
                    { 3, -7, -9, 11 },
                    { 12, -4, 2, 6 } };
    int n = 4;
 
    System.out.println("Maximum Sum = "+
                        maxSum(mat , n));
 
    }
}
 
// This code is contributed by Prerna Saini


Python3




# Python3 implementation to find
# the maximum sum path in a matrix
 
SIZE=10
INT_MIN=-10000000
 
# function to find the maximum sum
# path in a matrix
def maxSum(mat,n):
     
    #if there is a single elementif
    #there is a single element only
    if n==1:
        return mat[0][0]
         
    # dp[][] matrix to store the results
    # of each iteration
    dp=[[0 for i in range(n)]for i in range(n)]
    maxSum=INT_MIN
     
    # base case, copying elements of
    # last row
    for j in range(n):
        dp[n - 1][j] = mat[n - 1][j]
         
    # building up the dp[][] matrix from
    # bottom to the top row
    for i in range(n-2,-1,-1):
        for j in range(n):
            maxi=INT_MIN
             
            # finding the maximum diagonal
            # element in the
            # (i+1)th row if that cell exists
            if ((((j - 1) >= 0) and
               (maxi < dp[i + 1][j - 1]))):
                   maxi = dp[i + 1][j - 1]
            if ((((j + 1) < n) and
               (maxi < dp[i + 1][j + 1]))):
                   maxi = dp[i + 1][j + 1]
                 
            # adding that 'max' element to the
            # mat[i][j] element
            dp[i][j] = mat[i][j] + maxi
             
    # finding the maximum value from the
    # first row of dp[][]
    for j in range(n):
        if (maxSum < dp[0][j]):
            maxSum = dp[0][j]
             
    # required maximum sum
    return maxSum
 
# Driver program to test above
if __name__=='__main__':
    mat=[[5, 6, 1, 7],
        [-2, 10, 8, -1],
        [ 3, -7, -9, 11 ],
        [12, -4, 2, 6 ]]
 
    n=4
    print("Maximum Sum=",maxSum(mat,n))
     
#This code is contributed by sahilshelangia


C#




// C# implementation to find the
// maximum sum path in a matrix
using System;
 
class MaxSumPath
{
    //int mat[][];
     
    // function to find the maximum
    // sum path in a matrix
    static int maxSum(int[,] mat, int n)
    {
        // if there is a single element only
        if (n == 1)
            return mat[0, 0];
     
        // dp[][] matrix to store the results
        // of each iteration
        int [,]dp = new int[n, n];
        int maxSum = int.MinValue, max;
     
        // base case, copying elements of
        // last row
        for (int j = 0; j < n; j++)
            dp[n - 1, j] = mat[n - 1, j];
     
        // building up the dp[][] matrix
        // from bottom to the top row
        for (int i = n - 2; i >= 0; i--)
        {
            for (int j = 0; j < n; j++)
            {
                max = int.MinValue;
     
                // finding the maximum diagonal
                // element in the (i+1)th row
                // if that cell exists
                if (((j - 1) >= 0) &&
                    (max < dp[i + 1, j - 1]))
                    max = dp[i + 1, j - 1];
                if (((j + 1) < n) &&
                    (max < dp[i + 1, j + 1]))
                    max = dp[i + 1, j + 1];
     
                // adding that 'max' element
                // to the mat[i][j] element
                dp[i, j] = mat[i, j] + max;
            }
        }
     
        // finding the maximum value from
        // the first row of dp[][]
        for (int j = 0; j < n; j++)
            if (maxSum < dp[0, j])
                maxSum = dp[0, j];
     
        // required maximum sum
        return maxSum;
    }
 
    // Driver code
    public static void Main () {
     
    int [,]mat = { { 5, 6, 1, 7 },
                    { -2, 10, 8, -1 },
                    { 3, -7, -9, 11 },
                    { 12, -4, 2, 6 } };
    int n = 4;
 
    Console.WriteLine("Maximum Sum = "+
                        maxSum(mat , n));
 
    }
}
 
// This code is contributed by vt_m


Javascript




<script>
 
// JavaScript implementation to find the
// maximum sum path in a matrix
 
// Function to find the maximum
// sum path in a matrix
function maxSum(mat, n)
{
     
    // If there is a single element only
    if (n == 1)
        return mat[0][0];
   
    // dp[][] matrix to store the results
    // of each iteration
    let dp = new Array(n);
      
    // Loop to create 2D array using 1D array
    for(var i = 0; i < dp.length; i++)
    {
        dp[i] = new Array(2);
    }
     
    let maxSum = Number.MIN_VALUE, max;
   
    // Base case, copying elements of
    // last row
    for(let j = 0; j < n; j++)
        dp[n - 1][j] = mat[n - 1][j];
   
    // Building up the dp[][] matrix
    // from bottom to the top row
    for(let i = n - 2; i >= 0; i--)
    {
        for(let j = 0; j < n; j++)
        {
            max = Number.MIN_VALUE;
             
            // Finding the maximum diagonal
            // element in the (i+1)th row
            // if that cell exists
            if (((j - 1) >= 0) &&
               (max < dp[i + 1][j - 1]))
                 max = dp[i + 1][j - 1];
            if (((j + 1) < n) &&
               (max < dp[i + 1][j + 1]))
                max = dp[i + 1][j + 1];
   
            // Adding that 'max' element
            // to the mat[i][j] element
            dp[i][j] = mat[i][j] + max;
        }
    }
   
    // Finding the maximum value from
    // the first row of dp[][]
    for(let j = 0; j < n; j++)
        if (maxSum < dp[0][j])
            maxSum = dp[0][j];
   
    // Required maximum sum
    return maxSum;
}
   
// Driver Code
let mat = [ [ 5, 6, 1, 7 ],
            [ -2, 10, 8, -1 ],
            [ 3, -7, -9, 11 ],
            [ 12, -4, 2, 6 ] ];
let n = 4;
 
document.write("Maximum Sum = "+
               maxSum(mat , n));
                
// This code is contributed by sanjoy_62
 
</script>


PHP




<?php
// PHP implementation to find
// the maximum sum path in a matrix
 
$SIZE = 10;
 
// function to find the maximum sum
// path in a matrix
function maxSum( $mat, $n)
{
     
    // if there is a single
    // element only
    if ($n == 1)
        return $mat[0][0];
 
    // dp[][] matrix to store the results
    // of each iteration
    $dp = array(array());
    $maxSum = PHP_INT_MIN;
    $max;
 
    // base case, copying elements of
    // last row
    for($j = 0; $j < $n; $j++)
        $dp[$n - 1][$j] = $mat[$n - 1][$j];
 
    // building up the dp[][] matrix from
    // bottom to the top row
    for ( $i = $n - 2; $i >= 0; $i--)
    {
        for ( $j = 0; $j < $n; $j++)
        {
            $max = PHP_INT_MIN;
 
            // finding the maximum
            // diagonal element in the
            // (i+1)th row if that cell
            // exists
            if ((($j - 1) >= 0) and
                ($max < $dp[$i + 1][$j - 1]))
                 
                $max = $dp[$i + 1][$j - 1];
                 
            if ((($j + 1) < $n) and ($max <
                      $dp[$i + 1][$j + 1]))
                       
                $max = $dp[$i + 1][$j + 1];
 
            // adding that 'max' element to the
            // mat[i][j] element
            $dp[$i][$j] = $mat[$i][$j] + $max;
        }
    }
 
    // finding the maximum value from the
    // first row of dp[][]
    for ( $j = 0; $j < $n; $j++)
        if ($maxSum < $dp[0][$j])
            $maxSum = $dp[0][$j];
 
    // required maximum sum
    return $maxSum;
}
 
    // Driver Code
    $mat = array(array(5, 6, 1, 7),
                 array(-2, 10, 8, -1),
                 array(3, -7, -9, 11),
                 array(12, -4, 2, 6));
    $n = 4;
    echo "Maximum Sum = "
        , maxSum($mat, $n);
 
// This code is contributed by anuj_67.
?>


Output

Maximum Sum = 28





Time Complexity: O(n2). 
Auxiliary Space: O(n2).

Method 2: Space-optimized approach:

To solve this problem with space complexity O(1), we can modify the input matrix itself to store the maximum sum that can be obtained up to each cell. In other words, we can use the same matrix to represent both the input matrix and the dynamic programming table.

We can start by initializing the first row of the matrix with the same values as the first row of the input matrix. Then, for each subsequent row i, we can update the values of the matrix using the values of the previous row, along with the value of the current cell in the input matrix.

The recurrence relation for the matrix can be expressed as:
mat[i][j] = max(mat[i-1][j-1], mat[i-1][j+1]) + mat[i][j]

After updating all the values in the matrix, the maximum sum can be obtained by finding the maximum value in the last row of the matrix. 

Step-by-step approach:

  • The first row of the matrix is left unchanged. 
  • For each subsequent row of the matrix, the maximum sum path is calculated. For this, another for loop is used to iterate through each element of the row.
  • The value of the current element in the matrix is updated by adding it to the maximum of its two adjacent elements in the previous row, i.e., the element to its top-right and top-left.
  • Then, find the maximum sum in the last row of the matrix

Below is the implementation of the above approach:

C++




#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
 
using namespace std;
 
int max_sum_path(vector<vector<int>>& mat) {
    int n = mat.size();
     
    // Update the values of the matrix for each subsequent row
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int left = (j > 0) ? mat[i-1][j-1] : INT_MIN;
            int right = (j < n-1) ? mat[i-1][j+1] : INT_MIN;
            mat[i][j] += max(left, right);
        }
    }
     
    // Find the maximum sum in the last row of the matrix
    return *max_element(mat[n-1].begin(), mat[n-1].end());
}
 
int main() {
    vector<vector<int>> mat = {{5, 6, 1, 7},
                               {-2, 10, 8, -1},
                               {3, -7, -9, 11},
                               {12, -4, 2, 6}};
    cout << max_sum_path(mat) << endl;  // Output: 28
    return 0;
}


Java




import java.util.Arrays;
 
public class MaxSumPath {
    // Function to find the maximum sum path in a matrix
    static int maxSumPath(int[][] mat)
    {
        int n = mat.length;
 
        // Update the values of the matrix for each
        // subsequent row
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int left = (j > 0) ? mat[i - 1][j - 1]
                                   : Integer.MIN_VALUE;
                int right = (j < n - 1) ? mat[i - 1][j + 1]
                                        : Integer.MIN_VALUE;
                mat[i][j] += Math.max(left, right);
            }
        }
 
        // Find the maximum sum in the last row of the
        // matrix
        int maxSum
            = Arrays.stream(mat[n - 1]).max().getAsInt();
        return maxSum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[][] mat = { { 5, 6, 1, 7 },
                        { -2, 10, 8, -1 },
                        { 3, -7, -9, 11 },
                        { 12, -4, 2, 6 } };
 
        System.out.println(maxSumPath(mat)); // Output: 28
    }
}


Python3




def max_sum_path(mat):
    n = len(mat)
     
    # Update the values of the matrix for each subsequent row
    for i in range(1, n):
        for j in range(n):
            left = mat[i-1][j-1] if j > 0 else float('-inf')
            right = mat[i-1][j+1] if j < n-1 else float('-inf')
            mat[i][j] += max(left, right)
     
    # Find the maximum sum in the last row of the matrix
    return max(mat[-1])
 
if __name__ == "__main__":
    mat = [[5, 6, 1, 7],
           [-2, 10, 8, -1],
           [3, -7, -9, 11],
           [12, -4, 2, 6]]
    print(max_sum_path(mat)) 


C#




using System;
using System.Collections.Generic;
using System.Linq; // Add the System.Linq namespace for the Max method
 
class Program
{
    static int MaxSumPath(List<List<int>> mat)
    {
        int n = mat.Count;
 
        // Update the values of the matrix for each subsequent row
        for (int i = 1; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int left = (j > 0) ? mat[i - 1][j - 1] : int.MinValue;
                int right = (j < n - 1) ? mat[i - 1][j + 1] : int.MinValue;
                mat[i][j] += Math.Max(left, right);
            }
        }
 
        // Find the maximum sum in the last row of the matrix
        int[] lastRow = mat[n - 1].ToArray();
        return lastRow.Max(); // Use the Max method from System.Linq
    }
 
    static void Main()
    {
        List<List<int>> mat = new List<List<int>>
        {
            new List<int> {5, 6, 1, 7},
            new List<int> {-2, 10, 8, -1},
            new List<int> {3, -7, -9, 11},
            new List<int> {12, -4, 2, 6}
        };
        Console.WriteLine(MaxSumPath(mat));  // Output: 28
    }
}


Javascript




function maxSumPath(mat) {
    const n = mat.length;
 
    // Update the values of the matrix for each subsequent row
    for (let i = 1; i < n; i++) {
        for (let j = 0; j < n; j++) {
            let left = (j > 0) ? mat[i-1][j-1] : Number.MIN_SAFE_INTEGER;
            let right = (j < n-1) ? mat[i-1][j+1] : Number.MIN_SAFE_INTEGER;
            mat[i][j] += Math.max(left, right);
        }
    }
 
    // Find the maximum sum in the last row of the matrix
    const maxSum = Math.max(...mat[n-1]);
    return maxSum;
}
 
// Driver program
const mat = [
    [5, 6, 1, 7],
    [-2, 10, 8, -1],
    [3, -7, -9, 11],
    [12, -4, 2, 6]
];
 
console.log(maxSumPath(mat));  // Output: 28


Output

28





Time Complexity: O(n^2). 
Auxiliary Space: O(1).



Last Updated : 07 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads