Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Pair with maximum sum in a Matrix
Next article icon

Find row with maximum sum in a Matrix

Last Updated : 12 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an N*N matrix. The task is to find the index of a row with the maximum sum. That is the row whose sum of elements is maximum.

Examples: 

Input : mat[][] = {
            { 1, 2, 3, 4, 5 },
            { 5, 3, 1, 4, 2 },
            { 5, 6, 7, 8, 9 },
            { 0, 6, 3, 4, 12 },
            { 9, 7, 12, 4, 3 },
            }; 

Output : Row 3 has max sum 35

Input : mat[][] = { 
          { 1, 2, 3 },
          { 4, 2, 1 },
          { 5, 6, 7 },
          };
Output : Row 3 has max sum 18

The idea is to traverse the matrix row-wise and find the sum of elements in each row and check for every row if current sum is greater than the maximum sum obtained till the current row and update the maximum_sum accordingly. 

Algorithm:

  • Define a constant N as the number of rows and columns in the matrix.
  • Define a function colMaxSum that takes a 2D array of integers mat of size N*N as its input.
  • Initialize two variables idx and maxSum to -1 and INT_MIN respectively.
  • Traverse the matrix row-wise.
  • For each row, calculate the sum of all the elements in that row.
  • If the sum of the current row is greater than the current maxSum, update maxSum to be the sum of the current row and set idx to be the index of the current row.
  • Return a pair of integers, with the first element being the index of the row with the maximum sum (idx) and the second element being the maximum sum (maxSum).

Pseudocode:

1. N ? number of rows and columns in the matrix 2. function colMaxSum(mat[N][N]) 3.     idx ? -1 4.     maxSum ? INT_MIN 5.     for i from 0 to N-1 6.         sum ? 0 7.         for j from 0 to N-1 8.             sum ? sum + mat[i][j] 9.         if sum > maxSum 10.            maxSum ? sum 11.            idx ? i 12.    return pair(idx, maxSum) 13. end function

Below is the implementation of the above approach:

C++




// C++ program to find row with
// max sum in a matrix
#include <bits/stdc++.h>
using namespace std;
 
#define N 5 // No of rows and column
 
// Function to find the row with max sum
pair<int, int> colMaxSum(int mat[N][N])
{
    // Variable to store index of row
    // with maximum
    int idx = -1;
 
    // Variable to store max sum
    int maxSum = INT_MIN;
 
    // Traverse matrix row wise
    for (int i = 0; i < N; i++) {
        int sum = 0;
 
        // calculate sum of row
        for (int j = 0; j < N; j++) {
            sum += mat[i][j];
        }
 
        // Update maxSum if it is less than
        // current sum
        if (sum > maxSum) {
            maxSum = sum;
 
            // store index
            idx = i;
        }
    }
 
    pair<int, int> res;
 
    res = make_pair(idx, maxSum);
 
    // return result
    return res;
}
 
// Driver code
int main()
{
 
    int mat[N][N] = {
        { 1, 2, 3, 4, 5 },  { 5, 3, 1, 4, 2 },
        { 5, 6, 7, 8, 9 },  { 0, 6, 3, 4, 12 },
        { 9, 7, 12, 4, 3 },
    };
 
    pair<int, int> ans = colMaxSum(mat);
 
    cout << "Row " << ans.first + 1 << " has max sum "
         << ans.second;
 
    return 0;
}
 
 

Java




// Java program to find row with
// max sum in a matrix
import java.util.ArrayList;
 
class MaxSum {
    public static int N;
 
    static ArrayList<Integer> colMaxSum(int mat[][])
    {
        // Variable to store index of row
        // with maximum
        int idx = -1;
 
        // Variable to store maximum sum
        int maxSum = Integer.MIN_VALUE;
 
        // Traverse the matrix row wise
        for (int i = 0; i < N; i++) {
            int sum = 0;
            for (int j = 0; j < N; j++) {
                sum += mat[i][j];
            }
 
            // Update maxSum if it is less than
            // current row sum
            if (maxSum < sum) {
                maxSum = sum;
 
                // store index
                idx = i;
            }
        }
 
        // Arraylist to store values of index
        // of maximum sum and the maximum sum together
        ArrayList<Integer> res = new ArrayList<>();
        res.add(idx);
        res.add(maxSum);
 
        return res;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        N = 5;
        int[][] mat = {
            { 1, 2, 3, 4, 5 },  { 5, 3, 1, 4, 2 },
            { 5, 6, 7, 8, 9 },  { 0, 6, 3, 4, 12 },
            { 9, 7, 12, 4, 3 },
        };
        ArrayList<Integer> ans = colMaxSum(mat);
        System.out.println("Row " + (ans.get(0) + 1)
                           + " has max sum " + ans.get(1));
    }
}
 
// This code is contributed by Vivekkumar Singh
 
 

Python3




# Python3 program to find row with
# max sum in a matrix
import sys
 
N = 5  # No of rows and column
 
# Function to find the row with max sum
 
 
def colMaxSum(mat):
 
    # Variable to store index of row
    # with maximum
    idx = -1
 
    # Variable to store max sum
    maxSum = -sys.maxsize
 
    # Traverse matrix row wise
    for i in range(0, N):
        sum = 0
 
        # calculate sum of row
        for j in range(0, N):
            sum += mat[i][j]
 
        # Update maxSum if it is less than
        # current sum
        if (sum > maxSum):
            maxSum = sum
 
            # store index
            idx = i
 
    res = [idx, maxSum]
 
    # return result
    return res
 
 
# Driver code
mat = [[1, 2, 3, 4, 5],
       [5, 3, 1, 4, 2],
       [5, 6, 7, 8, 9],
       [0, 6, 3, 4, 12],
       [9, 7, 12, 4, 3]]
 
ans = colMaxSum(mat)
print("Row", ans[0] + 1, "has max sum", ans[1])
 
# This code is contributed by Sanjit_Prasad
 
 

C#




// C# program to find row with
// max sum in a matrix
using System;
using System.Collections.Generic;
 
public class MaxSum {
    public static int N;
 
    static List<int> colMaxSum(int[, ] mat)
    {
        // Variable to store index of row
        // with maximum
        int idx = -1;
 
        // Variable to store maximum sum
        int maxSum = int.MinValue;
 
        // Traverse the matrix row wise
        for (int i = 0; i < N; i++) {
            int sum = 0;
            for (int j = 0; j < N; j++) {
                sum += mat[i, j];
            }
 
            // Update maxSum if it is less than
            // current row sum
            if (maxSum < sum) {
                maxSum = sum;
 
                // store index
                idx = i;
            }
        }
 
        // Arraylist to store values of index
        // of maximum sum and the maximum sum together
        List<int> res = new List<int>();
        res.Add(idx);
        res.Add(maxSum);
 
        return res;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        N = 5;
        int[, ] mat = {
            { 1, 2, 3, 4, 5 },  { 5, 3, 1, 4, 2 },
            { 5, 6, 7, 8, 9 },  { 0, 6, 3, 4, 12 },
            { 9, 7, 12, 4, 3 },
        };
        List<int> ans = colMaxSum(mat);
        Console.WriteLine("Row " + (ans[0] + 1)
                          + " has max sum " + ans[1]);
    }
}
 
// This code has been contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript program to find row with
// max sum in a matrix
var N;
function colMaxSum(mat)
{
    // Variable to store index of row
    // with maximum
    var idx = -1;
    // Variable to store maximum sum
    var maxSum = -1000000000;
    // Traverse the matrix row wise
    for (var i = 0; i < N; i++)
    {
        var sum = 0;
        for (var j = 0; j < N; j++)
        {
            sum += mat[i][j];
        }
        // Update maxSum if it is less than
        // current row sum
        if (maxSum < sum)
        {
            maxSum = sum;
            // store index
            idx = i;
        }
    }
     
    // Arraylist to store values of index
    // of maximum sum and the maximum sum together
    var res = [];
    res.push(idx);
    res.push(maxSum);
    return res;
}
// Driver code
N = 5;
var mat = [
    [ 1, 2, 3, 4, 5 ],
    [ 5, 3, 1, 4, 2 ],
    [ 5, 6, 7, 8, 9 ],
    [ 0, 6, 3, 4, 12],
    [ 9, 7, 12, 4, 3]];
var ans = colMaxSum(mat);
document.write("Row "+ (ans[0]+1)+ " has max sum "
+ ans[1]);
 
 
</script>
 
 
Output
Row 3 has max sum 35

Time complexity: O(N2)
Auxiliary space: O(1)

Example in c:

Approach:

Initialize a variable max_sum to zero and a variable max_row to -1.

Traverse the matrix row by row:

a. Initialize a variable row_sum to zero.

b. Traverse the elements of the current row and add them to row_sum.

c. If row_sum is greater than max_sum, update max_sum to row_sum and max_row to the current row.

Return max_row.

C




#include <stdio.h>
 
int main()
{
    int mat[3][4] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 } };
 
    int m = 3;
    int n = 4;
 
    int max_sum = 0;
    int max_row = -1;
 
    // Traverse the matrix row by row and find the row with
    // maximum sum
    for (int i = 0; i < m; i++) {
        int row_sum = 0;
        for (int j = 0; j < n; j++) {
            row_sum += mat[i][j];
        }
        if (row_sum > max_sum) {
            max_sum = row_sum;
            max_row = i;
        }
    }
 
    printf("Row with maximum sum is: %d\n", max_row);
 
    return 0;
}
 
 

C++




#include <iostream>
using namespace std;
 
int main()
{
    int mat[3][4] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 } };
 
    int m = 3;
    int n = 4;
 
    int max_sum = 0;
    int max_row = -1;
 
    // Traverse the matrix row by row and find the row with
    // maximum sum
    for (int i = 0; i < m; i++) {
        int row_sum = 0;
        for (int j = 0; j < n; j++) {
            row_sum += mat[i][j];
        }
        if (row_sum > max_sum) {
            max_sum = row_sum;
            max_row = i;
        }
    }
 
    cout << "Row with maximum sum is: " << max_row << endl;
 
    return 0;
}
 
 

Java




class Main {
    public static void main(String[] args)
    {
        int[][] mat = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 } };
 
        int m = 3;
        int n = 4;
 
        int max_sum = 0;
        int max_row = -1;
 
        // Traverse the matrix row by row and find the row
        // with maximum sum
        for (int i = 0; i < m; i++) {
            int row_sum = 0;
            for (int j = 0; j < n; j++) {
                row_sum += mat[i][j];
            }
            if (row_sum > max_sum) {
                max_sum = row_sum;
                max_row = i;
            }
        }
 
        System.out.println("Row with maximum sum is: "
                           + max_row);
    }
}
 
 

Python3




# Create a 3x4 matrix
mat = [[1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12]]
m = 3
n = 4
 
# Initialize max_sum and max_row to 0
max_sum = 0
max_row = -1
 
# Traverse the matrix row by row and find the row with maximum sum
for i in range(m):
    row_sum = 0
    for j in range(n):
        row_sum += mat[i][j]
    if row_sum > max_sum:
        max_sum = row_sum
        max_row = i
 
# Print the index of the row with maximum sum
print("Row with maximum sum is: ", max_row)
 
 

Javascript




// Create a 3x4 matrix
let mat = [[1, 2, 3, 4],
           [5, 6, 7, 8],
           [9, 10, 11, 12]];
let m = 3;
let n = 4;
 
// Initialize max_sum and max_row to 0
let max_sum = 0;
let max_row = -1;
 
// Traverse the matrix row by row and find the row with maximum sum
for (let i = 0; i < m; i++) {
    let row_sum = 0;
    for (let j = 0; j < n; j++) {
        row_sum += mat[i][j];
    }
    if (row_sum > max_sum) {
        max_sum = row_sum;
        max_row = i;
    }
}
 
// Print the index of the row with maximum sum
console.log("Row with maximum sum is: ", max_row);
 
 

C#




using System;
 
class GFG {
 
    public static void Main(string[] args)
    {
        int[][] mat
            = new int[][] { new int[] { 1, 2, 3, 4 },
                            new int[] { 5, 6, 7, 8 },
                            new int[] { 9, 10, 11, 12 } };
        int m = 3;
        int n = 4;
 
        // Initialize max_sum and max_row to 0
        int max_sum = 0;
        int max_row = -1;
 
        // Traverse the matrix row by row and find the row
        // with maximum sum
        for (int i = 0; i < m; i++) {
            int row_sum = 0;
            for (int j = 0; j < n; j++) {
                row_sum += mat[i][j];
            }
            if (row_sum > max_sum) {
                max_sum = row_sum;
                max_row = i;
            }
        }
 
        // Print the index of the row with maximum sum
        Console.WriteLine("Row with maximum sum is: "
                          + max_row);
    }
}
 
 
Output
Row with maximum sum is: 2

time complexity of O(mn) 

 space complexity of O(n)



Next Article
Pair with maximum sum in a Matrix

B

barykrg
Improve
Article Tags :
  • DSA
  • Matrix
  • Traversal
Practice Tags :
  • Matrix
  • Traversal

Similar Reads

  • Find column with maximum sum in a Matrix
    Given a N*N matrix. The task is to find the index of column with maximum sum. That is the column whose sum of elements are maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Column 5 has max sum 31 Input
    7 min read
  • Pair with maximum sum in a Matrix
    Given a NxM matrix with N rows and M columns of positive integers. The task is to find the sum of pair with maximum sum in the matrix. Examples: Input : mat[N][M] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output : 41 Pair (25, 16) has the maximum sum Input : mat[N][M] = {{1,
    7 min read
  • Pair with maximum difference in a Matrix
    Given a NxM matrix with N rows and M columns of positive integers. The task is to find the pair with the maximum difference in the given matrix. Note: Pairs at positions (a, b) and (b, a) are considered equivalent. Examples: Input : mat[N][M] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14,
    5 min read
  • Maximum sum path in a Matrix
    Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum
    15+ min read
  • Program to find the maximum element in a Matrix
    Given an NxM matrix. The task is to find the maximum element in this matrix. Examples: Input: mat[4][4] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Output: 25 Input: mat[3][4] = {{9, 8, 7, 6}, {5, 4, 3, 2}, {1, 0, 12, 45}}; Output: 45 Approach: The idea is to traverse the mat
    6 min read
  • Maximum sum of elements from each row in the matrix
    Given a matrix, find the maximum sum we can have by selecting just one element from every row. Condition is element selected from nth row must be strictly greater than element from (n-1)th row, else no element must be taken from row. Print the sum if possible else print -1. Examples : Input : 1 2 31
    7 min read
  • Find Matrix With Given Row and Column Sums
    Given two arrays rowSum[] and colSum[] of size n and m respectively, the task is to construct a matrix of dimensions n × m such that the sum of matrix elements in every ith row is rowSum[i] and the sum of matrix elements in every jth column is colSum[j]. Note: The resultant matrix can have only non-
    15 min read
  • Find the maximum sum path in the given Matrix
    Consider an infinite matrix. The cells of the matrix are filled with natural numbers from the cell (1, 1) in the direction of top right to bottom left diagonally. Then the task is to output the Maximum path sum between two points (X1, Y1) and (X2, Y2). Matrix filling process is as follows: Examples:
    7 min read
  • Find Column with Maximum Zeros in Matrix
    Given a matrix(2D array) M of size N*N consisting of 0s and 1s only. The task is to find the column with the maximum number of 0s. If more than one column exists, print the one which comes first. If the maximum number of 0s is 0 then return -1. Examples: Input: N = 3, M[][] = {{0, 0, 0}, {1, 0, 1},
    5 min read
  • Maximum path sum in matrix
    Given a matrix of size n * m. Find the maximum path sum in the matrix. The maximum path is the sum of all elements from the first row to the last row where you are allowed to move only down or diagonally to left or right. You can start from any element in the first row. Examples: Input: mat[][] = 10
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences