Find row with maximum sum in a Matrix in C++


In this problem, we are given a matrix mat[][] of size N*N. Our task is to Find the row with maximum sum in a Matrix.

Let’s take an example to understand the problem,

Input

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

Output

Row 2, sum 24

Explanation

Row 1: sum = 8+4+1+9 = 22
Row 2: sum = 3+5+7+9 = 24
Row 3: sum = 2+4+6+8 = 20
Row 4: sum = 1+2+3+4 = 10

Solution Approach

A simple solution to the problem is to find the sum of elements of each row and keep a track of maximum sum. Then after all rows are traversed return the row with maximum sum.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
#define R 4
#define C 4
void findMax1Row(int mat[R][C]) {
   int maxSumRow = 0, maxSum = -1;
   int i, index;
   for (i = 0; i < R; i++) {
      int sum = 0;
      for(int j = 0; j < C; j++){
         sum += mat[i][j];
      }
      if(sum > maxSum){
         maxSum = sum;
         maxSumRow = i;
      }
   }
   cout<<"Row : "<<(maxSumRow+1)<<" has the maximum sum
   which is "<<maxSum;
}
int main() {
   int mat[R][C] = {
      {8, 4, 1, 9},
      {3, 5, 7, 9},
      {2, 4, 6, 8},
      {1, 2, 3, 4}
   };
   findMax1Row(mat);
   return 0;
}

Output

Row : 2 has the maximum sum which is 24

Updated on: 16-Mar-2021

827 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements