![]() |
In this problem, we are given a 2-D matrix and we have to find the maximum value of ‘MAT[a][b]’ – ‘MAT[d]’ over all possible indices (0 <= ‘a’, ‘b’, ‘c’, ‘d’ < ‘N’) such that . ‘a’ > ‘c’ and ‘b’ > ‘d’. Below is an example to understand the problem statement clearly Example: Input Below are different approaches to Find a specific pair in Matrix using JavaScript: Table of Content Brute force ApproachWe will initialize a variable answer with a value of negative infinity to store the maximum difference found in matrix. Now we iterate through each combination in matrix using nested loop making sure that ‘a’ > ‘c’ and ‘b’ > ‘d’. Update answer with the maximum difference found using Math.max(). Return answer as result. Example: To demonstrate finding a specific pair in Matrix using brute force approach
Output Maximum difference using Linear approach is 8 Time Complexity : O(N^4) Space Complexity: O(1) Optimal ApproachDefine a function that takes a 2D array mat. Initialize answer to store the maximum difference and maxArr to store maximum values from each position to the bottom-right corner. Preprocess the last row and column of maxArr, then traverse the matrix from bottom to top and right to left, updating answer and maxArr. Print the result stored in answer. Example: To demonstrate finding a specific pair in Matrix using optimal approach
Output Maximum difference using optimal approach is 8 Time Complexity: O(N^2) Space Complexity: O(N^2) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |