Maximum sum of elements from each row in the matrix in C++


In this problem, we are given a two matrix mat[][]. Our task is to create a program to find the maximum sum of elements from each row in the matrix in C++.

Problem Description

Here, we will find the maximum sum by taking one element from each row of the matrix in such a way that the element at the current row is greater than the last row element to be considered as a sum. We will find the maximum sum of elements that follows the above condition and print -1 if it is not possible.

Let’s take an example to understand the problem,

Input

mat[][] = {{4, 6, 1},
{2, 5, 7},
{9, 1, 2}}

Output

22

Explanation

1st row = 6
2nd row = 7
3rd row = 9
Sum = 6 + 7 + 9 = 22

Solution Approach

A simple solution is to start from the last row of the matrix. Find the largest number here and add to MaxSum and then move one row up, find the largest number less than the largest element of the row below it. Do this till you reach the top row. If we fail to find any number less than the maximum number then we will return -1.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
# define row 3
# define col 3

int RowMaxSum(int a[row][col]){
   int maxValLastRow = 10000;
   int maxSum = 0;
   for (int i = row - 1; i >= 0; i--){
      int maxNo = -1;
      for (int j = 0; j < col; j++)
         if (maxValLastRow > a[i][j] && a[i][j] > maxNo)
            maxNo = a[i][j];
      if (maxNo == -1)
         return -1;
      maxValLastRow = maxNo;
      maxSum += maxValLastRow;
   }
   return maxSum;
}
int main(){
   int a[3][3] = {{4, 6, 1},
                  {2, 5, 7},
                  {9, 1, 2}};
   cout<<"The maximum sum of elements from each row in the matrix is "<<RowMaxSum(a);
   return 0;
}

Output

The maximum sum of elements from each row in the matrix is 22

Updated on: 15-Oct-2020

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements