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
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Find maximum element of each row in a matrix
Next article icon

Maximum sum of elements from each row in the matrix

Last Updated : 13 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 3
1 2 3
7 8 9 
Output : 14 (2 + 3 + 9) (values we are adding are strictly increasing)

Input :
4 2 3
3 2 1
1 2 2\
Output : -1 
(No subsequent increasing elements can be picked from consecutive rows)

Approach:- One can simply run the loop from last row, get the greatest element from there say it prev_max, and keep record for the minimum difference among the elements of the row just above it, if any element found with positive difference, then add it to prev_max else print -1. Continue the same process for every row. 

Implementation:

C++




// CPP Program to find row-wise maximum element
// sum considering elements in increasing order.
#include <bits/stdc++.h>
#define N 3
using namespace std;
 
// Function to perform given task
int getGreatestSum(int a[][N])
{
    // Getting the maximum element from last row
    int prev_max = 0;
    for (int j = 0; j < N; j++)
        if (prev_max < a[N - 1][j])
            prev_max = a[N - 1][j];
 
    // Comparing it with the elements of above rows
    int sum = prev_max;
    for (int i = N - 2; i >= 0; i--) {
 
        // Maximum of current row.
        int curr_max = INT_MIN;
        for (int j = 0; j < N; j++)
            if (prev_max > a[i][j] && a[i][j] > curr_max)
                curr_max = a[i][j];
 
        // If we could not get an element smaller
        // than prev_max.
        if (curr_max == INT_MIN)
            return -1;
 
        prev_max = curr_max;
        sum += prev_max;
    }
    return sum;
}
 
// Driver code
int main()
{
    int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    cout << getGreatestSum(a) << endl;
    int b[3][3] = { { 4, 5, 6 }, { 4, 5, 6 }, { 4, 5, 6 } };
    cout << getGreatestSum(b) << endl;
    return 0;
}
 
 

Java




// Java Program to find row-wise maximum
// element sum considering elements in
// increasing order.
class GFG {
 
    static final int N = 3;
 
    // Function to perform given task
    static int getGreatestSum(int a[][])
    {
 
        // Getting the maximum element from
        // last row
        int prev_max = 0;
 
        for (int j = 0; j < N; j++)
            if (prev_max < a[N - 1][j])
                prev_max = a[N - 1][j];
 
        // Comparing it with the elements
        // of above rows
        int sum = prev_max;
 
        for (int i = N - 2; i >= 0; i--) {
 
            // Maximum of current row.
            int curr_max = -2147483648;
 
            for (int j = 0; j < N; j++)
                if (prev_max > a[i][j] && a[i][j] > curr_max)
                    curr_max = a[i][j];
 
            // If we could not an element smaller
            // than prev_max.
            if (curr_max == -2147483648)
                return -1;
 
            prev_max = curr_max;
            sum += prev_max;
        }
 
        return sum;
    }
 
    // Driver Program to test above function
    public static void main(String arg[])
    {
 
        int a[][] = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 } };
        System.out.println(getGreatestSum(a));
 
        int b[][] = { { 4, 5, 6 },
                      { 4, 5, 6 },
                      { 4, 5, 6 } };
        System.out.println(getGreatestSum(b));
    }
}
 
// This code is contributed by Anant Agarwal.
 
 

Python3




# Python Program to find
# row-wise maximum element
# sum considering elements
# in increasing order.
 
N = 3
 
# Function to perform given task
def getGreatestSum(a):
 
    # Getting the maximum
    # element from last row
    prev_max = 0
    for j in range(N):
        if (prev_max < a[N - 1][j]):
            prev_max = a[N - 1][j]
 
    # Comparing it with the
    # elements of above rows
    sum = prev_max
    for i in range(N - 2, -1, -1):
 
        # Maximum of current row.
        curr_max = -2147483648
        for j in range(N):
            if (prev_max > a[i][j] and a[i][j] > curr_max):
                curr_max = a[i][j]
 
        # If we could not an element smaller
        # than prev_max.
        if (curr_max == -2147483648):
            return -1
 
        prev_max = curr_max
        sum = sum + prev_max
     
    return sum
 
# Driver code
 
a = [ [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ] ]
 
print(getGreatestSum(a))
 
b = [ [ 4, 5, 6 ],
    [ 4, 5, 6 ],
    [ 4, 5, 6 ] ]
 
print(getGreatestSum(b))
     
# This code is contributed
# by Anant Agarwal.
 
 

C#




// C# Program to find row-wise maximum
// element sum considering elements in
// increasing order.
using System;
 
class GFG {
 
    static int N = 3;
 
    // Function to perform given task
    static int getGreatestSum(int[, ] a)
    {
 
        // Getting the maximum element from
        // last row
        int prev_max = 0;
 
        for (int j = 0; j < N; j++)
            if (prev_max < a[N - 1, j])
                prev_max = a[N - 1, j];
 
        // Comparing it with the elements
        // of above rows
        int sum = prev_max;
 
        for (int i = N - 2; i >= 0; i--) {
 
            // Maximum of current row.
            int curr_max = -2147483648;
 
            for (int j = 0; j < N; j++)
                if (prev_max > a[i, j] && a[i, j] > curr_max)
                    curr_max = a[i, j];
 
            // If we could not an element smaller
            // than prev_max.
            if (curr_max == -2147483648)
                return -1;
 
            prev_max = curr_max;
            sum += prev_max;
        }
 
        return sum;
    }
 
    // Driver Program
    public static void Main()
    {
 
        int[, ] a = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 } };
        Console.WriteLine(getGreatestSum(a));
 
        int[, ] b = { { 4, 5, 6 },
                      { 4, 5, 6 },
                      { 4, 5, 6 } };
        Console.WriteLine(getGreatestSum(b));
    }
}
 
// This code is contributed by vt_m.
 
 

PHP




<?php
// PHP Program to find
// row-wise maximum element
// sum considering elements
// in increasing order.
 
$N = 3;
 
// Function to perform given task
function getGreatestSum( $a)
{
    global $N;
     
    // Getting the maximum
    // element from last row
    $prev_max = 0;
 
    for ($j = 0; $j < $N; $j++)
        if ($prev_max < $a[$N - 1][$j])
            $prev_max = $a[$N - 1][$j];
 
    // Comparing it with the
    // elements of above rows
    $sum = $prev_max;
    for ($i = $N - 2; $i >= 0; $i--)
    {
 
        // Maximum of current row.
        $curr_max = PHP_INT_MIN;
        for ( $j = 0; $j < $N; $j++)
            if ($prev_max > $a[$i][$j] and
                $a[$i][$j] > $curr_max)
                $curr_max = $a[$i][$j];
 
        // If we could not an element
        // smaller than prev_max.
        if ($curr_max == PHP_INT_MIN)
            return -1;
 
        $prev_max = $curr_max;
        $sum += $prev_max;
    }
    return $sum;
}
 
// Driver code
$a = array(array(1, 2, 3),
        array(4, 5, 6),
        array(7, 8, 9));
             
echo getGreatestSum($a), "\n";
$b = array(array(4, 5, 6),
        array(4, 5, 6),
        array(4, 5, 6));
             
echo getGreatestSum($b), "\n";
 
// This code is contributed by anuj_67.
?>
 
 

Javascript




<script>
 
// JavaScript Program to find row-wise maximum
// element sum considering elements in
// increasing orderers
 
let N = 3;
   
    // Function to perform given task
    function getGreatestSum(a)
    {
   
        // Getting the maximum element from
        // last row
        let prev_max = 0;
   
        for (let j = 0; j < N; j++)
            if (prev_max < a[N - 1][j])
                prev_max = a[N - 1][j];
   
        // Comparing it with the elements
        // of above rows
        let sum = prev_max;
   
        for (let i = N - 2; i >= 0; i--) {
   
            // Maximum of current row.
            let curr_max = -2147483648;
   
            for (let j = 0; j < N; j++)
                if (prev_max > a[i][j] && a[i][j] > curr_max)
                    curr_max = a[i][j];
   
            // If we could not an element smaller
            // than prev_max.
            if (curr_max == -2147483648)
                return -1;
   
            prev_max = curr_max;
            sum += prev_max;
        }
   
        return sum;
    }
   
   
 
// Driver Code
 
        let a = [[ 1, 2, 3 ],
                      [ 4, 5, 6 ],
                      [ 7, 8, 9 ]];
        document.write(getGreatestSum(a) + "<br/>");
   
        let b = [[ 4, 5, 6 ],
                      [ 4, 5, 6 ],
                      [4, 5, 6 ]];
        document.write(getGreatestSum(b));
        
</script>
 
 
Output
18 15

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



Next Article
Find maximum element of each row in a matrix

S

Sakshi_Tiwari
Improve
Article Tags :
  • DSA
  • Matrix
  • Searching
Practice Tags :
  • Matrix
  • Searching

Similar Reads

  • 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 sum of K elements selected from a Matrix
    Given a positive integer K and a matrix arr[][] of dimensions N*M consisting of integers, the task is to find the maximum sum of K elements possible from the given matrix. Examples: Input: arr[][] = {10, 10, 100, 30}, {80, 50, 10, 50}}, K = 5Output: 310Explanation:Choose K(= 5) elements from the mat
    15+ 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
  • Maximum difference of sum of elements in two rows in a matrix
    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
    10 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 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
  • 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
  • Find maximum element of each column in a matrix
    Given a matrix, the task is to find the maximum element of each column. Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: 76 34 21 Input: [1, 2, 3, 21] [12, 1, 65, 9] 1, 56, 34, 2] Output: 12 56 65 21 Approach: The idea is to run the loop for no_of_cols. Check each element inside the column
    6 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
  • 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
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