# Maximum sum in a 2 x n grid such that no two elements are adjacent in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a rectangular grid of size 2 x n. Our task is to create a program to find the Maximum sum in a 2 x n grid such that no two elements are adjacent in C++.

## Problem Description

To find the maximum sum, we cannot select elements that are adjacent to the current element, vertically, horizontally or diagonally.

Let’s take an example to understand the problem,

## Input

rectGrid[2][] =389
411

## Output

13

## Explanation

all possible sums are

If we start from rectGrid[0][0] i.e. 3, then we can add only 9 or 1. The maxSum is 12.

If we start from rectGrid[1][0] i.e. 4, then we can add only 9 or 1. The maxSum is 13.

If we start from rectGrid[0][1] i.e. 8, then we cannot add any element. The maxSum is 8.

If we start from rectGrid[1][1] i.e. 1, then we cannot add any element. The maxSum is 1.

If we start from rectGrid[0][2] i.e. 9, then we can add only 3 or 4. The maxSum is 13.

If we start from rectGrid[1][2] i.e. 1, then we can add only 3 or 4. The maxSum is 5.

The overall maximum sum is 13.

## Solution Approach

The problem is similar to maximum sum such that no two elements are adjacent that we have seen in the last post. The difference is the array which is 2D here and the condition for adjacent elements. So, we will be considering the maximum element using conditions for both rows and columns. As each column has two rows, we will take maximum possible consideration of alternate elements.

## Example

Program to illustrate the working of solution,

Live Demo

#include<iostream>
using namespace std;
int findMax(int a, int b){
if(a > b)
return a;
return b;
}
int calcMaxSum(int rectGrid[2][20], int N){
int currectSum = 0;
int nextSum = 0;
int altSum;
for (int i = 0; i<N; i++ ){
altSum = findMax(nextSum, currectSum);
currectSum = nextSum + findMax(rectGrid[0][i], rectGrid[1][i]);
nextSum = altSum;
}
int maxSum = findMax(nextSum, currectSum);
return maxSum;
}
int main(){
int rectGrid[2][20] = {{3, 8, 9, 5},
{4, 1, 2, 7}};
int N = 4;
cout<<"The maximum sum in a 2 x "<<N<<" grid such that no two elements are adjacent is "<<calcMaxSum(rectGrid, N);
return 0;
}

## Output

The maximum sum in a 2 x 4 grid such that no two elements are adjacent is 15
Published on 22-Jul-2020 08:16:55