Maximize sum by selecting contiguous elements from each row or column
Last Updated :
30 Nov, 2022
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.
C++
#include <bits/stdc++.h>
using namespace std;
int max_contiguous_sum(vector< int >& arr)
{
int curr_sum = 0;
int max_sum = INT_MIN;
for ( int i = 0; i < arr.size(); i++) {
curr_sum += arr[i];
if (curr_sum > max_sum) {
max_sum = curr_sum;
}
if (curr_sum < 0) {
curr_sum = 0;
}
}
return max_sum;
}
int maxSum(vector<vector< int > >& mat, int m, int n)
{
int row_sum = 0;
int col_sum = 0;
for ( int i = 0; i < m; i++) {
vector< int > temp;
for ( int j = 0; j < n; j++) {
temp.push_back(mat[i][j]);
}
row_sum += max_contiguous_sum(temp);
}
for ( int i = 0; i < m; i++) {
vector< int > temp;
for ( int j = 0; j < n; j++) {
temp.push_back(mat[j][i]);
}
col_sum += max_contiguous_sum(temp);
}
int ans = max(row_sum, col_sum);
return ans;
}
int main()
{
vector<vector< int > > mat = { { -3, 0, -5 - 8 },
{ 4, -3, 4, -2 },
{ 4, 3, -8, 6 },
{ -1, -1, -1, -1 } };
int M = mat.size();
int N = mat[0].size();
int ans = maxSum(mat, M, N);
cout << ans << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static int max_contiguous_sum(ArrayList<Integer> arr)
{
int curr_sum = 0 ;
int max_sum = Integer.MIN_VALUE;
for ( int i = 0 ; i < arr.size(); i++) {
curr_sum += arr.get(i);
if (curr_sum > max_sum) {
max_sum = curr_sum;
}
if (curr_sum < 0 ) {
curr_sum = 0 ;
}
}
return max_sum;
}
static int maxSum( int [][] mat, int m, int n)
{
int row_sum = 0 ;
int col_sum = 0 ;
for ( int i = 0 ; i < m; i++) {
ArrayList<Integer> temp
= new ArrayList<Integer>();
for ( int j = 0 ; j < n; j++) {
temp.add(mat[i][j]);
}
row_sum += max_contiguous_sum(temp);
}
for ( int i = 0 ; i < m; i++) {
ArrayList<Integer> temp
= new ArrayList<Integer>();
for ( int j = 0 ; j < n; j++) {
temp.add(mat[j][i]);
}
col_sum += max_contiguous_sum(temp);
}
int ans = Math.max(row_sum, col_sum);
return ans;
}
public static void main(String[] args)
{
int [][] mat = { { - 3 , 0 , - 5 , - 8 },
{ 4 , - 3 , 4 , - 2 },
{ 4 , 3 , - 8 , 6 },
{ - 1 , - 1 , - 1 , - 1 } };
int M = 4 ;
int N = 4 ;
int ans = maxSum(mat, M, N);
System.out.println(ans);
}
}
|
Python3
def max_contiguous_sum(arr):
curr_sum = 0
max_sum = - 2147483647 - 1
for i in range ( 0 , len (arr)):
curr_sum + = arr[i]
if (curr_sum > max_sum):
max_sum = curr_sum
if (curr_sum < 0 ):
curr_sum = 0
return max_sum
def maxSum(mat, m, n):
row_sum = 0
col_sum = 0
for i in range ( 0 ,m):
temp = []
for j in range ( 0 ,n):
temp.append(mat[i][j])
row_sum + = max_contiguous_sum(temp)
for i in range ( 0 , 4 ):
temp = []
for j in range ( 0 , 3 ):
temp.append(mat[j][i])
col_sum + = max_contiguous_sum(temp)
ans = max (row_sum, col_sum)
return ans
mat = [ [ - 3 , 0 , - 5 , - 8 ],
[ 4 , - 3 , 4 , - 2 ],
[ 4 , 3 , - 8 , 6 ],
[ - 1 , - 1 , - 1 , - 1 ] ]
M = len (mat)
N = len (mat[ 0 ])
ans = maxSum(mat, M, N)
print (ans)
|
C#
using System;
public class GFG {
static int max_contiguous_sum( int [] arr)
{
int curr_sum = 0;
int max_sum = int .MinValue;
for ( int i = 0; i < arr.Length; i++) {
curr_sum += arr[i];
if (curr_sum > max_sum) {
max_sum = curr_sum;
}
if (curr_sum < 0) {
curr_sum = 0;
}
}
return max_sum;
}
static int maxSum( int [, ] mat, int m, int n)
{
int row_sum = 0;
int col_sum = 0;
for ( int i = 0; i < m; i++) {
int [] temp = new int [n];
for ( int j = 0; j < n; j++) {
temp[j] = (mat[i, j]);
}
row_sum += max_contiguous_sum(temp);
}
for ( int i = 0; i < m; i++) {
int [] temp = new int [n];
for ( int j = 0; j < n; j++) {
temp[j] = (mat[j, i]);
}
col_sum += max_contiguous_sum(temp);
}
int ans = Math.Max(row_sum, col_sum);
return ans;
}
static public void Main()
{
int [, ] mat = { { -3, 0, -5, -8 },
{ 4, -3, 4, -2 },
{ 4, 3, -8, 6 },
{ -1, -1, -1, -1 } };
int M = mat.GetLength(0);
int N = mat.GetLength(1);
int ans = maxSum(mat, M, N);
Console.WriteLine(ans);
}
}
|
Javascript
function max_contiguous_sum( arr)
{
let curr_sum = 0;
let max_sum = Number.MIN_VALUE;
for (let i = 0; i < arr.length; i++) {
curr_sum += arr[i];
if (curr_sum > max_sum) {
max_sum = curr_sum;
}
if (curr_sum < 0) {
curr_sum = 0;
}
}
return max_sum;
}
function maxSum(mat, m, n)
{
let row_sum = 0;
let col_sum = 0;
for (let i = 0; i < m; i++) {
let temp = [];
for (let j = 0; j < n; j++) {
temp.push(mat[i][j]);
}
row_sum += max_contiguous_sum(temp);
}
for (let i = 0; i < m; i++) {
temp = [];
for (let j = 0; j < n; j++) {
temp.push(mat[j][i]);
}
col_sum += max_contiguous_sum(temp);
}
let ans = Math.max(row_sum, col_sum);
return ans;
}
let mat = [ [ -3, 0, -5, - 8 ],[ 4, -3, 4, -2 ],
[ 4, 3, -8, 6 ],[ -1, -1, -1, -1 ] ];
let M = mat.length;
let N = mat[0].length;
let ans = maxSum(mat, M, N);
console.log(ans);
|
Time Complexity: O(M * N)
Space Complexity: O(max(M, N))
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...