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:
Maximum product of 4 adjacent elements in matrix
Next article icon

Maximum difference of sum of elements in two rows in a matrix

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a matrix of m*n order, the task is to find the maximum difference between two rows Rj and Ri such that i < j, i.e., we need to find maximum value of sum(Rj) - sum(Ri) such that row i is above row j.

Examples: 

Input : mat[5][4] = {{-1, 2, 3, 4},                       {5, 3, -2, 1},                       {6, 7, 2, -3},                       {2, 9, 1, 4},                       {2, 1, -2, 0}}  Output: 9  // difference of R3 - R1 is maximum

A simple solution for this problem is to one by one select each row, compute sum of elements in it and take difference from sum of next rows in forward direction. Finally return the maximum difference. Time complexity for this approach will be O(n*m2).

An efficient solution solution for this problem is to first calculate the sum of all elements of each row and store them in an auxiliary array rowSum[] and then calculate maximum difference of two elements max(rowSum[j] - rowSum[i]) such that rowSum[i] < rowSum[j] in linear time. See this article. In this method, we need to keep track of 2 things: 

  1. Maximum difference found so far (max_diff). 
  2. Minimum number visited so far (min_element). 

Implementation:

C++
// C++ program to find maximum difference of sum of // elements of two rows #include<bits/stdc++.h> #define MAX 100 using namespace std;  // Function to find maximum difference of sum of // elements of two rows such that second row appears // before first row. int maxRowDiff(int mat[][MAX], int m, int n) {     // auxiliary array to store sum of all elements     // of each row     int rowSum[m];      // calculate sum of each row and store it in     // rowSum array     for (int i=0; i<m; i++)     {         int sum = 0;         for (int j=0; j<n; j++)             sum += mat[i][j];         rowSum[i] = sum;     }      // calculating maximum difference of two elements     // such that rowSum[i]<rowsum[j]     int max_diff = rowSum[1] - rowSum[0];     int min_element = rowSum[0];     for (int i=1; i<m; i++)     {         // if current difference is greater than         // previous then update it         if (rowSum[i] - min_element > max_diff)             max_diff = rowSum[i] - min_element;          // if new element is less than previous minimum         // element then update it so that         // we may get maximum difference in remaining array         if (rowSum[i] < min_element)             min_element = rowSum[i];     }      return max_diff; }  // Driver program to run the case int main() {     int m = 5, n = 4;     int mat[][MAX] = {{-1, 2, 3, 4},                      {5, 3, -2, 1},                      {6, 7, 2, -3},                      {2, 9, 1, 4},                      {2, 1, -2, 0}};      cout << maxRowDiff(mat, m, n);     return 0; } 
C
// C program to find maximum difference of sum of // elements of two rows #include <stdio.h>  #define MAX 100  // Function to find maximum difference of sum of // elements of two rows such that second row appears // before first row. int maxRowDiff(int mat[][MAX], int m, int n) {     // auxiliary array to store sum of all elements     // of each row     int rowSum[m];      // calculate sum of each row and store it in     // rowSum array     for (int i=0; i<m; i++)     {         int sum = 0;         for (int j=0; j<n; j++)             sum += mat[i][j];         rowSum[i] = sum;     }      // calculating maximum difference of two elements     // such that rowSum[i]<rowsum[j]     int max_diff = rowSum[1] - rowSum[0];     int min_element = rowSum[0];     for (int i=1; i<m; i++)     {         // if current difference is greater than         // previous then update it         if (rowSum[i] - min_element > max_diff)             max_diff = rowSum[i] - min_element;          // if new element is less than previous minimum         // element then update it so that         // we may get maximum difference in remaining array         if (rowSum[i] < min_element)             min_element = rowSum[i];     }      return max_diff; }  // Driver program to run the case int main() {     int m = 5, n = 4;     int mat[][MAX] = {{-1, 2, 3, 4},                      {5, 3, -2, 1},                      {6, 7, 2, -3},                      {2, 9, 1, 4},                      {2, 1, -2, 0}};     printf("%d",maxRowDiff(mat, m, n));        return 0; }  // This code is contributed by kothavvsaakash. 
Java
// Java program to find maximum difference // of sum of elements of two rows import java.io.*; class GFG { static final int MAX = 100;  // Function to find maximum difference of sum  // of elements of two rows such that second  // row appears before first row. static int maxRowDiff(int mat[][], int m, int n) {      // auxiliary array to store sum      // of all elements of each row     int rowSum[] = new int[m];      // calculate sum of each row and      // store it in rowSum array     for (int i = 0; i < m; i++) {     int sum = 0;     for (int j = 0; j < n; j++)         sum += mat[i][j];     rowSum[i] = sum;     }      // calculating maximum difference of two elements     // such that rowSum[i]<rowsum[j]     int max_diff = rowSum[1] - rowSum[0];     int min_element = rowSum[0];     for (int i = 1; i < m; i++) {      // if current difference is greater than     // previous then update it     if (rowSum[i] - min_element > max_diff)         max_diff = rowSum[i] - min_element;      // if new element is less than previous      // minimum element then update it so that     // we may get maximum difference in remaining array     if (rowSum[i] < min_element)         min_element = rowSum[i];     }      return max_diff; }  // Driver code public static void main(String[] args) {     int m = 5, n = 4;     int mat[][] = {{-1, 2,  3, 4 },                      {5,  3, -2, 1 },                     {6,  7,  2, -3},                    {2,  9,  1, 4 },                    {2,  1, -2, 0}};      System.out.print(maxRowDiff(mat, m, n)); } } // This code is contributed by Anant Agarwal. 
Python3
# Python3 program to find maximum difference  # of sum of elements of two rows  # Function to find maximum difference of  # sum of elements of two rows such that  # second row appears before first row. def maxRowDiff(mat, m, n):          # auxiliary array to store sum of      # all elements of each row     rowSum = [0] * m          # calculate sum of each row and      # store it in rowSum array     for i in range(0, m):         sum = 0         for j in range(0, n):             sum += mat[i][j]          rowSum[i] = sum          # calculating maximum difference of      # two elements such that      # rowSum[i]<rowsum[j]     max_diff = rowSum[1] - rowSum[0]      min_element = rowSum[0]          for i in range(1, m):              # if current difference is greater          # than previous then update it         if (rowSum[i] - min_element > max_diff):             max_diff = rowSum[i] - min_element                  # if new element is less than previous         # minimum element then update it so          # that we may get maximum difference          # in remaining array         if (rowSum[i] < min_element):             min_element = rowSum[i]      return max_diff   # Driver program to run the case m = 5 n = 4 mat = [[-1, 2, 3, 4],        [5, 3, -2, 1],        [6, 7, 2, -3],        [2, 9, 1, 4],        [2, 1, -2, 0]]  print( maxRowDiff(mat, m, n))  # This code is contributed by Swetank Modi 
C#
// C# program to find maximum difference // of sum of elements of two rows using System;  class GFG {          // Function to find maximum difference      // of sum of elements of two rows such     // that second row appears before     // first row.     static int maxRowDiff(int [,] mat,                                int m, int n)     {              // auxiliary array to store sum          // of all elements of each row         int [] rowSum = new int[m];              // calculate sum of each row and          // store it in rowSum array         for (int i = 0; i < m; i++)         {             int sum = 0;                          for (int j = 0; j < n; j++)                 sum += mat[i,j];                              rowSum[i] = sum;         }              // calculating maximum difference         // of two elements such that          // rowSum[i] < rowsum[j]         int max_diff = rowSum[1] - rowSum[0];         int min_element = rowSum[0];                  for (int i = 1; i < m; i++)         {                  // if current difference is              // greater than previous then              // update it             if (rowSum[i] - min_element                                    > max_diff)                 max_diff = rowSum[i]                               - min_element;                      // if new element is less than             // previous minimum element then             // update it so that we may get              // maximum difference in              // remaining array             if (rowSum[i] < min_element)                 min_element = rowSum[i];         }              return max_diff;     }          // Driver code     public static void Main()     {         int m = 5, n = 4;         int [,] mat = { {-1, 2, 3, 4 },                         {5, 3, -2, 1 },                         {6, 7, 2, -3},                         {2, 9, 1, 4 },                         {2, 1, -2, 0} };              Console.Write(maxRowDiff(mat, m, n));     } }  // This code is contributed by KRV. 
PHP
<?php // PHP program to find maximum  // difference of sum of // elements of two rows $MAX = 100;  // Function to find maximum  // difference of sum of // elements of two rows such // that second row appears // before first row. function maxRowDiff($mat, $m, $n) {     global $MAX;     // auxiliary array to store     // sum of all elements     // of each row     $rowSum = array();      // calculate sum of each      // row and store it in     // rowSum array     for ($i = 0; $i < $m; $i++)     {         $sum = 0;         for ($j = 0; $j < $n; $j++)             $sum += $mat[$i][$j];         $rowSum[$i] = $sum;     }      // calculating maximum      // difference of two      // elements such that      // rowSum[i]<rowsum[j]     $max_diff = $rowSum[1] - $rowSum[0];     $min_element = $rowSum[0];     for ($i = 1; $i < $m; $i++)     {         // if current difference          // is greater than         // previous then update it         if ($rowSum[$i] - $min_element > $max_diff)             $max_diff = $rowSum[$i] - $min_element;          // if new element is less          // than previous minimum         // element then update it          // so that we may get maximum         // difference in remaining array         if ($rowSum[$i] < $min_element)             $min_element = $rowSum[$i];     }      return $max_diff; }  // Driver Code $m = 5; $n = 4; $mat = array(array(-1, 2, 3, 4),              array(5, 3, -2, 1),              array(6, 7, 2, -3),              array(2, 9, 1, 4),              array(2, 1, -2, 0));  echo maxRowDiff($mat, $m, $n);  // This code is contributed by ajit ?> 
JavaScript
<script>  // Javascript program to find maximum difference // of sum of elements of two rows  // Function to find maximum difference  // of sum of elements of two rows such // that second row appears before // first row. function maxRowDiff(mat, m, n) {        // Auxiliary array to store sum      // of all elements of each row     let rowSum = new Array(m);        // Calculate sum of each row and      // store it in rowSum array     for(let i = 0; i < m; i++)     {         let sum = 0;                    for(let j = 0; j < n; j++)             sum += mat[i][j];                        rowSum[i] = sum;     }        // Calculating maximum difference     // of two elements such that      // rowSum[i] < rowsum[j]     let max_diff = rowSum[1] - rowSum[0];     let min_element = rowSum[0];            for(let i = 1; i < m; i++)     {            // If current difference is          // greater than previous then          // update it         if (rowSum[i] - min_element > max_diff)             max_diff = rowSum[i] - min_element;                // If new element is less than         // previous minimum element then         // update it so that we may get          // maximum difference in          // remaining array         if (rowSum[i] < min_element)             min_element = rowSum[i];     }     return max_diff; }  // Driver code let m = 5, n = 4; let mat = [ [ -1, 2, 3, 4 ],             [ 5, 3, -2, 1 ],             [ 6, 7, 2, -3 ],             [ 2, 9, 1, 4  ],             [ 2, 1, -2, 0 ] ];  document.write(maxRowDiff(mat, m, n));  // This code is contributed by divyesh072019     </script> 

Output
9

Time Complexity : O(m*n) 
Auxiliary Space : O(m)

 


Next Article
Maximum product of 4 adjacent elements in matrix

S

Shashank Mishra ( Gullu )
Improve
Article Tags :
  • Matrix
  • DSA
Practice Tags :
  • Matrix

Similar Reads

  • 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 maximum element of each row in a matrix
    Given a matrix mat[][], the task is to find the maximum element of each row. Examples: Input: mat[][] = [[1, 2, 3] [1, 4, 9] [76, 34, 21]]Output :3976Input: mat[][] = [[1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]]Output :216556 The idea is to run the loop for no_of_rows. Check each element inside the
    4 min read
  • Maximum product of 4 adjacent elements in matrix
    Given a square matrix, find the maximum product of four adjacent elements of the matrix. The adjacent elements of the matrix can be top, down, left, right, diagonal, or anti-diagonal. The four or more numbers should be adjacent to each other. Note: n should be greater than or equal to 4 i.e n >=
    15+ min read
  • Javascript Program to Find maximum element of each row in a matrix
    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 :3976Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]Output :216556Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element insid
    2 min read
  • Sum of all maximum frequency elements in Matrix
    Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all maximum occurring elements in the given matrix. That is the sum of all such elements whose frequency is even in the matrix. Examples: Input : mat[] = {{1, 1, 1}, {2, 3, 3}, {4, 5, 3}} Output : 12 The max
    6 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
  • Minimum sum of all absolute differences of same column elements in adjacent rows in a given Matrix
    Given a matrix mat[][] having N rows and M columns, the task is to find the minimum distance between two adjacent rows where the distance between two rows is defined as the sum of all absolute differences between two elements present at the same column in the two rows. Examples: Input: mat[][] = {{1
    5 min read
  • Maximum sum of elements in a diagonal parallel to the main diagonal of a given Matrix
    Give a square matrix mat[][] of dimensions N * N, the task is to find the maximum sum of elements present in the given matrix along the diagonals which are parallel to the main diagonal. Below is the image of the same. Examples: Input: mat[][] = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9,
    11 min read
  • Find pair of rows in a binary matrix that has maximum bit difference
    Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has maximum bit difference Examples: Input: mat[][] = {{1, 1, 1, 1}, {1, 1, 0, 1}, {0, 0, 0, 0}}; Output : (1, 3) Bit difference between row numbers 1 and 3 is maximum with value 4. Bit difference between 1 and 2 is
    15 min read
  • Find row with maximum sum in a Matrix
    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 :
    11 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