Find a specific pair in matrix
Pattern: Matrix traversal
The largest mat[c][d] - mat[a][b] where the second cell is strictly below and to the right of the first. Fill a table of the largest value in each bottom-right block, walking from the bottom-right corner, and compare each cell with the block just past it.
The problem
You are given an n × n matrix of whole numbers, with n ≥ 2. Find the largest value of mat[c][d] - mat[a][b] over
all choices where c > a and d > b. So the second cell must be strictly lower and strictly further right. For
example, [[1, 2], [3, 4]] gives 4 - 1 = 3, and [[4, 3], [2, 1]] gives 1 - 4 = -3.
The link above is a GeeksforGeeks article. The function name findMaxValue is this guide's own. The answer can be
negative when every valid pair goes downhill.
Think first
- Fix the first cell
(a, b). Which cells may the second one be, and which of them is best? - That set is a block from
(a + 1, b + 1)to the bottom-right corner. Can you know the largest value of every such block in advance? - In which order can those block maximums be filled so each one uses ones already filled?
Hints
Brute force, and why it fails
Try every first cell and every second cell: four nested loops, O(n⁴). This guide uses that to check its tests. The table of block maximums brings it to O(n²).
The key insight
This is Best Time to Buy and Sell Stock in two dimensions. Instead of the best price later in time, you want the best value lower and further right, and a table filled from the far corner keeps that ready for every cell.
Dry run
| best | none |
|---|
mat has rows 1 2, 3 4. The only valid pair is the cell at (0, 0) with the cell at (1, 1). Walk from the bottom-right corner backwards.
The plan
best = minus infinity
for i from n - 1 down to 0:
for j from n - 1 down to 0:
high[i][j] = mat[i][j]
if i + 1 < n: high[i][j] = max(high[i][j], high[i + 1][j])
if j + 1 < n: high[i][j] = max(high[i][j], high[i][j + 1])
if i + 1 < n and j + 1 < n:
best = max(best, high[i + 1][j + 1] - mat[i][j])
return best
Complexity
- Time
O(n²)- Space
O(n²)
Each cell is handled once with O(1) work. The high table takes n² cells.
Edge cases
n = 2: only one valid pair, the top-left cell with the bottom-right one.- Every value equal: the answer is 0.
- Values falling to the bottom-right: the answer is negative, so do not start
bestat 0.
I've built my logic, show the code
Java
class Solution {
public int findMaxValue(int[][] mat) {
int n = mat.length;
int best = Integer.MIN_VALUE;
int[][] high = new int[n][n]; // high[i][j] = largest value in the block from (i, j) to (n-1, n-1)
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
high[i][j] = mat[i][j];
if (i + 1 < n) high[i][j] = Math.max(high[i][j], high[i + 1][j]);
if (j + 1 < n) high[i][j] = Math.max(high[i][j], high[i][j + 1]);
if (i + 1 < n && j + 1 < n) best = Math.max(best, high[i + 1][j + 1] - mat[i][j]);
}
}
return best;
}
}C++
class Solution {
public:
int findMaxValue(vector<vector<int>>& mat) {
int n = static_cast<int>(mat.size());
vector<vector<int>> high(n, vector<int>(n)); // high[i][j] = largest value from (i, j) to (n-1, n-1)
int best = INT_MIN;
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
high[i][j] = mat[i][j];
if (i + 1 < n) high[i][j] = max(high[i][j], high[i + 1][j]);
if (j + 1 < n) high[i][j] = max(high[i][j], high[i][j + 1]);
if (i + 1 < n && j + 1 < n) best = max(best, high[i + 1][j + 1] - mat[i][j]);
}
}
return best;
}
};Python
class Solution:
def findMaxValue(self, mat: list[list[int]]) -> int:
n = len(mat)
high = [[0] * n for _ in range(n)] # high[i][j] = largest value from (i, j) to (n-1, n-1)
best = None
for i in range(n - 1, -1, -1):
for j in range(n - 1, -1, -1):
high[i][j] = mat[i][j]
if i + 1 < n:
high[i][j] = max(high[i][j], high[i + 1][j])
if j + 1 < n:
high[i][j] = max(high[i][j], high[i][j + 1])
if i + 1 < n and j + 1 < n:
v = high[i + 1][j + 1] - mat[i][j]
best = v if best is None else max(best, v)
return bestCommon mistakes
- Using
high[i][j]instead ofhigh[i + 1][j + 1], which lets a cell pair with itself or with its own row. - Starting
bestat 0, which gives the wrong answer when every pair goes downhill. - Filling the table from the top-left, so the cells it needs are not ready yet.