Largest Row or Column
For a given two-dimensional integer array/list of size (N x M), you need to find out which row or column has the largest sum(sum of all the elements in a row/column) amongst all the rows and columns.
Note :
Input Format :
Output Format :
Consider :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
#include <iostream>
using namespace std;
#include "solution.h"
#include<climits>
void findLargest(int **a, int m, int n)
{
//Write your code here
if(m==0 && n==0){
cout<<"row"<<" "<<n<<" "<< INT_MIN;
}
else{
long int sum_row[n]={0};
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
sum_row[i]=sum_row[i]+a[i][j];
}
}
int count_row=0;
int max_row=INT_MIN;
for(int i=0;i<n;i++){
if(sum_row[i]>max_row){
max_row=sum_row[i];
count_row=i;
}
}
long int sum_col[n]={0};
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
sum_col[j]=sum_col[j]+a[i][j];
}
}
int count_column=0;
int max_column=INT_MIN;
for(int i=0;i<n;i++){
if(sum_col[i]>max_column){
max_column=sum_col[i];
count_column=i;
}
}
if(max_row>=max_column){
cout<<"row"<<" "<<count_row<<" "<< sum_row[count_row];
}
else{
cout<<"column"<<" "<<count_column<<" "<< sum_col[count_column];
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
int row, col;
cin >> row >> col;
int **input = new int *[row];
for (int i = 0; i < row; i++)
{
input[i] = new int[col];
for (int j = 0; j < col; j++)
{
cin >> input[i][j];
}
}
findLargest(input, row, col);
cout << endl;
}
}
Comments
Post a Comment