VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-specific-pair-in-matrix/

⇱ Find a specific pair in Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find a specific pair in Matrix

Last Updated : 23 Jul, 2025

Given an n x n matrix mat[n][n] of integers, find the maximum value of mat(c, d) - mat(a, b) over all choices of indexes such that both c > a and d > b.

Example:

Input:
mat[N][N] = {{ 1, 2, -1, -4, -20 },
{ -8, -3, 4, 2, 1 },
{ 3, 8, 6, 1, 3 },
{ -4, -1, 1, 7, -6 },
{ 0, -4, 10, -5, 1 }};
Output: 18
The maximum value is 18 as mat[4][2]
- mat[1][0] = 18 has maximum difference.

The program should do only ONE traversal of the matrix. i.e. expected time complexity is O(n2)
A simple solution would be to apply Brute-Force. For all values mat(a, b) in the matrix, we find mat(c, d) that has maximum value such that c > a and d > b and keeps on updating maximum value found so far. We finally return the maximum value.

Below is its implementation. 


Output
Maximum Value is 18

Time complexity:O(N4).
Auxiliary Space: O(1)

The above program runs in O(n^4) time which is nowhere close to expected time complexity of O(n^2)

An efficient solution uses extra space. We pre-process the matrix such that index(i, j) stores max of elements in matrix from (i, j) to (N-1, N-1) and in the process keeps on updating maximum value found so far. We finally return the maximum value.

Implementation:


Output
Maximum Value is 18

Time complexity: O(N2).
Auxiliary Space: O(N2)

If we are allowed to modify of the matrix, we can avoid using extra space and use input matrix instead.

Exercise: Print index (a, b) and (c, d) as well.

An optimal approach is with space complexity O(N).

Instead of using the maxArr matrix, we can use two separate vectors (temp1 and temp2) to get maxArr[i+1][j] and maxArr[i][j+1] values.


Output
Maximum Value is 18

The time complexity of the findMaxValue() function is O(N^2) because it iterates over each element of the matrix exactly once.

The space complexity of the function is O(N) because it uses two vectors of size N (temp1 and temp2) to store the maximum values seen so far in each row and column.

This article is contributed by Aarti_Rathi and Aditya Goel.

Comment
Article Tags:
Article Tags: