
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum product of 4 adjacent elements in matrix in C++
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
#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
- Related Questions & Answers
- Maximum product of any two adjacent elements in JavaScript
- Maximum sum of difference of adjacent elements in C++
- JavaScript: Adjacent Elements Product Algorithm
- Maximum decreasing adjacent elements in JavaScript
- Maximum product quadruple (sub-sequence of size 4) in array in C++
- Maximum sum such that no two elements are adjacent in C++
- Maximum set bit sum in array without considering adjacent elements in C++
- Maximum Product of Word Lengths in C++
- Maximum Product of Three Numbers in C++
- Maximum sum of elements from each row in the matrix in C++
- Maximum sum such that no two elements are adjacent - Set 2 in C++
- Maximum difference of sum of elements in two rows in a matrix in C
- Maximum sum in circular array such that no two elements are adjacent in C++
- Maximum product subset of an array in C++
- Maximum product of an increasing subsequence in C++
Advertisements