
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Maximum product of any two adjacent elements in JavaScript
- Maximum sum of difference of adjacent elements in C++
- Maximum decreasing adjacent elements in JavaScript
- JavaScript: Adjacent Elements Product Algorithm
- Maximum sum such that no two elements are adjacent in C++
- Maximum set bit sum in array without considering adjacent elements in C++
- Maximum sum of elements from each row in the matrix in C++
- Maximum product quadruple (sub-sequence of size 4) in array 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 sum such that no two elements are adjacent - Set 2 in C++
- Maximum sum such that no two elements are adjacent Alternate Method in C++ program
- Maximum Product of Word Lengths in C++
- Maximum Product of Three Numbers in C++
- Maximum length subarray with difference between adjacent elements as either 0 or 1 in C++

Advertisements