Ninja And The Rows

Easy
0/40
Average time to solve is 15m
profile
Contributed by
12 upvotes
Asked in companies
AdobeAppleLTI - Larsen & Toubro Infotech

Problem statement

Ninja has been provided a matrix 'MAT' of size 'N X M' where 'M' is the number of columns in the matrix, and 'N' is the number of rows.

The weight of the particular row is the sum of all elements in it. Ninja wants to find the maximum weight amongst all the rows.

Your task is to help the ninja find the maximum weight amongst all the rows.

EXAMPLE:
Input: 'N' = 2, 'M' = 3, 'MAT' = [[1, 2, 3], [2, 0, 0]]
Output: 6

The weight of first row is 1 + 2 + 3 = 6
The weight of the second row is 2 + 0 + 0 = 2; hence the answer will be a maximum of 2 and 6, which is 6.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of input contains an integer 'T', denoting the number of test cases. 

For each test case, the first line will contain two integers, 'N' and 'M' number of rows and columns in the matrix. Next, 'N' lines will contain 'M' integers for each of the matrix elements.
Output format :
For each test case, print the maximum weight amongst all the rows.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 10
1 <= 'N' <= 10^2
1 <= 'M' <= 10^2
0 <= 'MAT[I][J]' <= 10^5

Time Limit: 1 sec
Sample Input 1 :
2
3 3
1 2 3
3 4 2
3 4 2
1 1
2
Sample Output 1 :
9
2
Explanation Of Sample Input 1 :
For the first test case, the answer will be 9. It will be formed by the 2nd row, and it will be the maximum amongst all.

For the first test case, as there is only one row, the answer will be its sum which is 2.
Sample Input 2 :
2
1 3
1 2 3
4 2
2 2
3 4 
2 4
4 5
Sample Output 2 :
6
9
Hint

Can you iterate over all the rows?

Approaches (1)
Brute force

Approach: In this approach, we will simply iterate over all the rows of the matrix and calculate the sum of each row. after that, we will track the maximum amongst all the sums, and the answer will be that maximum sum.
 

Algorithm :  

 

  1. Declare and Initialize the variable 'answer' by 0.
  2. Iterate over the vector 'mat' with iterator variable 'i'.
    • Declare and Initialize the variable 'current' by 0.
    • Iterate over the vector 'mat[i]' with iterator variable 'j'.
      • Update 'current' with 'current + mat[i][j]'.
    • Update 'answer' with 'max(answer, current)'.
  3. Return 'answer'.
Time Complexity

O(N * M), Where 'N' is the number of rows, and 'M' is the number of columns in the input matrix.

 

As we are iterating over the matrix of size 'N X M', the time complexity will be O(N * M).

Space Complexity

O(1)

 

As we are using constant extra space, the space complexity will be O(1)

Code Solution
(100% EXP penalty)
Ninja And The Rows
Full screen
Console