Maximum product of 4 adjacent elements in matrix in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum product of 4 adjacent elements in matrix.

For this we will be provided with a square matrix. Our task is to find the maximum product of four adjacent elements which can be top, down, right, left, or diagonal.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
const int n = 5;
//finding maximum product
int FindMaxProduct(int arr[][n], int n) {
   int max = 0, result;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         if ((j - 3) >= 0) {
            result = arr[i][j] * arr[i][j - 1] * arr[i][j - 2] * arr[i][j - 3];
            if (max < result)
               max = result;
         }
         //checking in vertical row
         if ((i - 3) >= 0) {
            result = arr[i][j] * arr[i - 1][j] * arr[i - 2][j] * arr[i - 3][j];
            if (max < result)
               max = result;
         }
         //checking in diagonal
         if ((i - 3) >= 0 && (j - 3) >= 0) { result = arr[i][j] * arr[i - 1][j - 1] * arr[i - 2][j - 2] * arr[i - 3][j - 3];
         if (max < result)
            max = result;
      }
      if ((i - 3) >= 0 && (j - 1) <= 0) {
         result = arr[i][j] * arr[i - 1][j + 1] * arr[i - 2][j + 2] * arr[i - 3][j + 3];
         if (max < result)
            max = result;
         }
      }
   }
   return max;
}
int main() {
   int arr[][5] = {
      {1, 2, 3, 4, 5},
      {6, 7, 8, 9, 1},
      {2, 3, 4, 5, 6},
      {7, 8, 9, 1, 0},
      {9, 6, 4, 2, 3}
   };
   cout << FindMaxProduct(arr, n);
   return 0;
}

Output

3024
raja
Published on 09-Sep-2020 16:24:21
Advertisements