VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-sum-by-selecting-contiguous-elements-from-each-row-or-column/

⇱ Maximize sum by selecting contiguous elements from each row or column - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize sum by selecting contiguous elements from each row or column

Last Updated : 23 Jul, 2025

Given a matrix mat[][] of size M x N where mat[i][j], the task is to find the maximum possible sum by picking contiguous elements from each or from each column.

Note: It is compulsory to pick at least one element from each row or column and you can perform this either in rows only or in columns only.

Examples: 

Input:  mat[][] = [ [-3, 0, -5, -8], [4, -3, 4, -2], [4, 3, -8, 6], [-1, -1, -1, -1] ]
Output: 21
Explanation: Max amount if  moving horizontally = 0(1st row) + 4 - 3 + 4 (2nd row) + 4 + 3 (3rd row) - 1 (4th row) = 0 + 5 + 7 - 1 = 11
Max amount  if moving vertically = 4+4 (1st column) + 3 (2nd row) + 4 (3rd row) + 6 (4th row) = 8 + 3 + 4 + 6 = 21
Maximum sum  = max(11, 21) = 21

Input:  mat = [ [-1, -2], [-1, -3] ]
Output:  -2

Approach:  The problem can be solved using Kadane's Algorithm based on the following idea: 

  • Store the maximum contiguous sum for each row in a variable row sum 
  • Store the maximum contiguous sum for each column in a variable col sum

If selecting elements only from row then the sum of row sums will be the maximum sum and if selecting columns only then the sum of columns will be the maximum column. The maximum among these two sums is the required answer.

Follow the steps mentioned below to implement the idea:

  • Traverse matrix mat[][] first of all row-wise and store each row in a vector and 
    • Find the maximum sum using Kadane's algorithm described above.
    • Add the maximum sum for each row in a variable rowsum.
  • Similarly, traverse matrix mat[][] column-wise and store each column in a vector and 
    • Find the maximum sum using Kadane's algorithm described above.
    • Add the maximum sum for each column in a variable colsum.
  • Maximum out of rowsum and colsum will be the maximum possible sum traversing it either horizontally or vertically.

Below is the implementation of the above approach.


Output
21

Time Complexity: O(M * N)
Space Complexity: O(max(M, N)) 

Comment