C++ Program to Find maximum element of each row in a matrix
Last Updated :
01 Dec, 2022
Given a matrix, the task is to find the maximum element of each row.
Examples:
Input : [1, 2, 3]
[1, 4, 9]
[76, 34, 21]
Output :
3
9
76
Input : [1, 2, 3, 21]
[12, 1, 65, 9]
[1, 56, 34, 2]
Output :
21
65
56
Approach : The approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum element. Finally, print the element.
Below is the implementation :
C++14
#include <bits/stdc++.h>
using namespace std;
const int N = 4;
void printArray(vector< int >& result, int no_of_rows)
{
for ( int i = 0; i < no_of_rows; i++) {
cout << result[i] << " " ;
}
}
void maxelement( int no_of_rows, vector<vector< int > >& arr)
{
int i = 0;
int max = 0;
vector< int > result(no_of_rows);
while (i < no_of_rows) {
for ( int j = 0; j < N; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
result[i] = max;
max = 0;
i++;
}
printArray(result, no_of_rows);
}
int main()
{
vector<vector< int > > arr = { { 3, 4, 1, 8 },
{ 1, 4, 9, 11 },
{ 76, 34, 21, 1 },
{ 2, 1, 4, 5 } };
maxelement(4, arr);
return 0;
}
|
Time Complexity: O(M*N), where M and N are no of rows and column of given matrix
Auxiliary Space: O(M)
Please refer complete article on Find maximum element of each row in a matrix for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...