VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-product-of-4-adjacent-elements-in-matrix/

⇱ Maximum product of 4 adjacent elements in matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum product of 4 adjacent elements in matrix

Last Updated : 10 Nov, 2022

Given a square matrix, find the maximum product of four adjacent elements of the matrix. The adjacent elements of the matrix can be top, down, left, right, diagonal, or anti-diagonal. The four or more numbers should be adjacent to each other. 

Note: n should be greater than or equal to 4 i.e n >= 4

Examples : 

Input : n = 4
           {{6, 2, 3 4},
            {5, 4, 3, 1},
           {7, 4, 5, 6},
          {8, 3, 1, 0}}
Output : 1680 
Explanation:
Multiplication of 6 5 7 8 produces maximum result and all element are adjacent to each other in one direction

Input : n = 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}}
Output: 3024
Explanation: Multiplication of 6 7 8 9 produces maximum result and all elements are adjacent to each other in one direction.

Asked in: Tolexo

Approach: 

  1. Group 4 elements that are adjacent to each other in each row and calculate their maximum result.
  2. Group 4 elements that are adjacent to each other in each column and calculate their maximum results.
  3. Group 4 elements that are adjacent to each other in diagonal and calculate their maximum results.
  4. Group 4 elements that are adjacent to each other in anti-diagonal and calculate their maximum results.
  5. Compare all calculated maximum results.

Below is the implementation of the above approach:


Output
3024

Time Complexity: O(n2)
Auxiliary Space: O(1), as no extra space is used

For row-wise adjacent elements, we can generalize the method using a sliding window.

Note: All elements in the matrix must be non-zero.

Another Approach:

  1. For each row, create a window of size k. Find the product of k adjacent element as window product (wp).
  2. Iterate through the row from k to  (row size), by sliding window approach, find the maximum product. Note: (row size)>=k.
  3. Assign the maximum product to a global maximum product.

Below is the implementation of the above approach:


Output
3024

Time Complexity: O(n2)
Auxiliary Space: O(1), as no extra space is used

Comment
Article Tags: