![]() |
VOOZH | about |
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 directionInput : 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:
- Group 4 elements that are adjacent to each other in each row and calculate their maximum result.
- Group 4 elements that are adjacent to each other in each column and calculate their maximum results.
- Group 4 elements that are adjacent to each other in diagonal and calculate their maximum results.
- Group 4 elements that are adjacent to each other in anti-diagonal and calculate their maximum results.
- Compare all calculated maximum results.
Below is the implementation of the above approach:
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:
- For each row, create a window of size k. Find the product of k adjacent element as window product (wp).
- Iterate through the row from k to (row size), by sliding window approach, find the maximum product. Note: (row size)>=k.
- Assign the maximum product to a global maximum product.
Below is the implementation of the above approach:
3024
Time Complexity: O(n2)
Auxiliary Space: O(1), as no extra space is used