- Related Questions & Answers
- Find maximum element of each row in a matrix in C++
- C++ program to find the Sum of each Row and each Column of a Matrix
- Program to find maximum sum by flipping each row elements in Python
- Find row with maximum sum in a Matrix in C++
- Maximum difference of sum of elements in two rows in a matrix in C
- How to find the row sum for each column by row name in an R matrix?
- Maximum sum of hour glass in matrix in C++
- Maximum path sum in matrix in C++
- Maximum sum of increasing order elements from n arrays in C++
- Find maximum element of each column in a matrix in C++
- Matrix row sum and column sum using C program
- Maximum sum of difference of adjacent elements in C++
- Maximum product of 4 adjacent elements in matrix in C++
- Maximum sum of increasing order elements from n arrays in C++ program
- Maximum sum path in a matrix from top to bottom in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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++.

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,**

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

22

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

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.

Program to illustrate the working of our solution,

#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; }

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

Advertisements