Tuesday, November 14, 2017

Largest Sum - NxN Matrix

A square matrix of size N*N is passed as input. The program must print the largest sum possible S across a row or a column.

Input Format:
The first line will contain the value of N. N lines will follow with each line containing N integer values separated by a space.

Boundary Conditions: 1 <= N <= 20

Output Format:
The largest possible sum across a given row or a column in the N*N square matrix.

Example Input/Output:
Input:
3
1 2 3
4 5 6
3 3 9
Output:
18
Explanation:
18 is the largest possible sum along the 3rd column (as 3+6+9 = 18)

Solution 1:
n,c=int(input()),0
a=[0]*n
for i in range(n):
    b=[int(j) for j in input().split()]
    c=max(c,sum(b))
    for y in range(n):
        a[y]+=b[y]
print(max(c,max(a)))

Solution 2:
#include <iostream>
using namespace std;
int main()
{
 int i,j,x,n,y,c=0;
 cin>>n;
 int a[n]={0};
 for(i=0;i<n;i++)
 {  
     y=0;
     for(j=0;j<n;j++)
     {
         cin>>x;
         y+=x;
         a[j]+=x;
     }
     c=max(c,y);
 }
 for(i=0;i<n;i++)
   c=max(c,a[i]);
 cout<<c;
}
Share: