# Maximum sum of increasing order elements from n arrays in C++ program

C++Server Side ProgrammingProgramming

In this problem, we are given a 2-D matrix of size nXm. Our task is to create a program to find the maximum sum of increasing order elements from n arrays.

Program Description − Here, we need to find the maximum sum of elements by taking one element from each row in such a way that the element from ith row is less than the element from (i+1)th row. And so on. If no such sum is possible, return −1 denoting no result possible.

Let’s take an example to understand the problem,

## Input

mat[][] = {
{4, 5, 1, 3, 6},
{5, 9, 2, 7, 12},
{13, 1, 3, 6, 8},
{10, 5, 7, 2, 4}
}

## Output

31

## Explanation

Taking elements from the matrix to create max Sum:
6 + 7 + 8 + 10 = 31,
6 From array 1, the maximum value.
7 from array 2, choosing 12(maximum value) cannot provide a solution.
8 from array 3, choosing 13(maximum value) cannot provide a solution.
10 From array 4, the maximum value

## Solution Approach

A solution to the problem is by selecting an element from the last array of the array of arrays and then going up selecting the largest possible element smaller than the given element.

Now, using this solution, we have one case when there is no element in ith array (row) which is less than the element at (i+1)th array (row). Here, we will be returning −1.

Sorting the array can be a good aid to the efficiency of our solution. As if we sort in increasing order, the largest element will be at index m−1, and the next will be smaller. Hence, finding the largest element satisfying the condition is easy.

## Algorithm

Initialise maxSum = 0, currMax

Step 1

Sort each array of the array of arrays (each will have elements in
increasing order).

Step 2

currMax = mat[n−1][m−1], the last element or the last row. Update
maxSum, maxSum = currMax.

Step 3

Loop through the matrix rowise, i = n−2 to 0.

Step 3.1

Find the max element in mat[i][] which is smaller than
currMax at index j.

Step 3.2

if j < 0, i.e. no value found. Return −1.

Step 3.3

Update currMax. currMax = mat[i][j].

Step 3.4

Update maxSum, maxSum = currMax.

Step 4

Return maxSum.

## Example

Program to illustrate the working of our solution,

Live Demo

#include <bits/stdc++.h>
#define M 5
using namespace std;
int calcMaxSumMat(int mat[][M], int n) {
for (int i = 0; i < n; i++)
sort(mat[i], mat[i] + M);
int maxSum = mat[n − 1][M − 1];
int currMax = mat[n − 1][M − 1];
int j;
for (int i = n − 2; i >= 0; i−−) {
for (j = M − 1; j >= 0; j−−) {
if (mat[i][j] < currMax) {
currMax = mat[i][j];
maxSum += currMax;
break;
}
}
if (j == −1)
return 0;
}
return maxSum;
}
int main() {
int mat[][M] = {
{4, 5, 1, 3, 6},
{5, 9, 2, 7, 12},
{12, 1, 3, 6, 8},
{10, 5, 7, 2, 4}
};
int n = sizeof(mat) / sizeof(mat);
cout<<"The maximum sum of increasing order elements from n arrays is "<<calcMaxSumMat(mat, n);
return 0;
}

## Output

The maximum sum of increasing order elements from n arrays is 31