
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements