Find a specific pair in Matrix
Last Updated :
06 Dec, 2023
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.
C++
// A Naive method to find maximum value of mat[d][e]
// - ma[a][b] such that d > a and e > b
#include <bits/stdc++.h>
using namespace std;
#define N 5
// The function returns maximum value A(d,e) - A(a,b)
// over all choices of indexes such that both d > a
// and e > b.
int findMaxValue(int mat[][N])
{
// stores maximum value
int maxValue = INT_MIN;
// Consider all possible pairs mat[a][b] and
// mat[d][e]
for (int a = 0; a < N - 1; a++)
for (int b = 0; b < N - 1; b++)
for (int d = a + 1; d < N; d++)
for (int e = b + 1; e < N; e++)
if (maxValue < (mat[d][e] - mat[a][b]))
maxValue = mat[d][e] - mat[a][b];
return maxValue;
}
// Driver program to test above function
int main()
{
int 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 }
};
cout << "Maximum Value is "
<< findMaxValue(mat);
return 0;
}
Java
// A Naive method to find maximum value of mat1[d][e]
// - ma[a][b] such that d > a and e > b
import java.io.*;
import java.util.*;
class GFG
{
// The function returns maximum value A(d,e) - A(a,b)
// over all choices of indexes such that both d > a
// and e > b.
static int findMaxValue(int N,int mat[][])
{
// stores maximum value
int maxValue = Integer.MIN_VALUE;
// Consider all possible pairs mat[a][b] and
// mat1[d][e]
for (int a = 0; a < N - 1; a++)
for (int b = 0; b < N - 1; b++)
for (int d = a + 1; d < N; d++)
for (int e = b + 1; e < N; e++)
if (maxValue < (mat[d][e] - mat[a][b]))
maxValue = mat[d][e] - mat[a][b];
return maxValue;
}
// Driver code
public static void main (String[] args)
{
int N = 5;
int mat[][] = {
{ 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 }
};
System.out.print("Maximum Value is " +
findMaxValue(N,mat));
}
}
// This code is contributed
// by Prakriti Gupta
Python 3
# A Naive method to find maximum
# value of mat[d][e] - mat[a][b]
# such that d > a and e > b
N = 5
# The function returns maximum
# value A(d,e) - A(a,b) over
# all choices of indexes such
# that both d > a and e > b.
def findMaxValue(mat):
# stores maximum value
maxValue = 0
# Consider all possible pairs
# mat[a][b] and mat[d][e]
for a in range(N - 1):
for b in range(N - 1):
for d in range(a + 1, N):
for e in range(b + 1, N):
if maxValue < int (mat[d][e] -
mat[a][b]):
maxValue = int(mat[d][e] -
mat[a][b]);
return maxValue;
# Driver Code
mat = [[ 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 ]];
print("Maximum Value is " +
str(findMaxValue(mat)))
# This code is contributed
# by ChitraNayal
C#
// A Naive method to find maximum
// value of mat[d][e] - mat[a][b]
// such that d > a and e > b
using System;
class GFG
{
// The function returns
// maximum value A(d,e) - A(a,b)
// over all choices of indexes
// such that both d > a
// and e > b.
static int findMaxValue(int N,
int [,]mat)
{
//stores maximum value
int maxValue = int.MinValue;
// Consider all possible pairs
// mat[a][b] and mat[d][e]
for (int a = 0; a< N - 1; a++)
for (int b = 0; b < N - 1; b++)
for (int d = a + 1; d < N; d++)
for (int e = b + 1; e < N; e++)
if (maxValue < (mat[d, e] -
mat[a, b]))
maxValue = mat[d, e] -
mat[a, b];
return maxValue;
}
// Driver code
public static void Main ()
{
int N = 5;
int [,]mat = {{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}};
Console.Write("Maximum Value is " +
findMaxValue(N,mat));
}
}
// This code is contributed
// by ChitraNayal
JavaScript
<script>
// A Naive method to find maximum value of mat1[d][e]
// - ma[a][b] such that d > a and e > b
// The function returns maximum value A(d,e) - A(a,b)
// over all choices of indexes such that both d > a
// and e > b.
function findMaxValue(N,mat)
{
// stores maximum value
let maxValue = Number.MIN_VALUE;
// Consider all possible pairs mat[a][b] and
// mat1[d][e]
for (let a = 0; a < N - 1; a++)
for (let b = 0; b < N - 1; b++)
for (let d = a + 1; d < N; d++)
for (let e = b + 1; e < N; e++)
if (maxValue < (mat[d][e] - mat[a][b]))
maxValue = mat[d][e] - mat[a][b];
return maxValue;
}
// Driver code
let N = 5;
let mat=[[ 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 ]];
document.write("Maximum Value is " +findMaxValue(N,mat));
// This code is contributed by rag2127
</script>
PHP
<?php
// A Naive method to find maximum
// value of $mat[d][e] - ma[a][b]
// such that $d > $a and $e > $b
$N = 5;
// The function returns maximum
// value A(d,e) - A(a,b) over
// all choices of indexes such
// that both $d > $a and $e > $b.
function findMaxValue(&$mat)
{
global $N;
// stores maximum value
$maxValue = PHP_INT_MIN;
// Consider all possible
// pairs $mat[$a][$b] and
// $mat[$d][$e]
for ($a = 0; $a < $N - 1; $a++)
for ($b = 0; $b < $N - 1; $b++)
for ($d = $a + 1; $d < $N; $d++)
for ($e = $b + 1; $e < $N; $e++)
if ($maxValue < ($mat[$d][$e] -
$mat[$a][$b]))
$maxValue = $mat[$d][$e] -
$mat[$a][$b];
return $maxValue;
}
// Driver Code
$mat = array(array(1, 2, -1, -4, -20),
array(-8, -3, 4, 2, 1),
array(3, 8, 6, 1, 3),
array(-4, -1, 1, 7, -6),
array(0, -4, 10, -5, 1));
echo "Maximum Value is " .
findMaxValue($mat);
// This code is contributed
// by ChitraNayal
?>
OutputMaximum 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:
C++
// An efficient method to find maximum value of mat[c][d]
// - ma[a][b] such that c > a and d > b
#include <bits/stdc++.h>
using namespace std;
#define N 5
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
int findMaxValue(int mat[][N])
{
//stores maximum value
int maxValue = INT_MIN;
// maxArr[i][j] stores max of elements in matrix
// from (i, j) to (N-1, N-1)
int maxArr[N][N];
// last element of maxArr will be same's as of
// the input matrix
maxArr[N-1][N-1] = mat[N-1][N-1];
// preprocess last row
int maxv = mat[N-1][N-1]; // Initialize max
for (int j = N - 2; j >= 0; j--)
{
if (mat[N-1][j] > maxv)
maxv = mat[N - 1][j];
maxArr[N-1][j] = maxv;
}
// preprocess last column
maxv = mat[N - 1][N - 1]; // Initialize max
for (int i = N - 2; i >= 0; i--)
{
if (mat[i][N - 1] > maxv)
maxv = mat[i][N - 1];
maxArr[i][N - 1] = maxv;
}
// preprocess rest of the matrix from bottom
for (int i = N-2; i >= 0; i--)
{
for (int j = N-2; j >= 0; j--)
{
// Update maxValue
if (maxArr[i+1][j+1] - mat[i][j] >
maxValue)
maxValue = maxArr[i + 1][j + 1] - mat[i][j];
// set maxArr (i, j)
maxArr[i][j] = max(mat[i][j],
max(maxArr[i][j + 1],
maxArr[i + 1][j]) );
}
}
return maxValue;
}
// Driver program to test above function
int main()
{
int 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 }
};
cout << "Maximum Value is "
<< findMaxValue(mat);
return 0;
}
Java
// An efficient method to find maximum value of mat1[d]
// - ma[a][b] such that c > a and d > b
import java.io.*;
import java.util.*;
class GFG
{
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
static int findMaxValue(int N,int mat[][])
{
//stores maximum value
int maxValue = Integer.MIN_VALUE;
// maxArr[i][j] stores max of elements in matrix
// from (i, j) to (N-1, N-1)
int maxArr[][] = new int[N][N];
// last element of maxArr will be same's as of
// the input matrix
maxArr[N-1][N-1] = mat[N-1][N-1];
// preprocess last row
int maxv = mat[N-1][N-1]; // Initialize max
for (int j = N - 2; j >= 0; j--)
{
if (mat[N-1][j] > maxv)
maxv = mat[N - 1][j];
maxArr[N-1][j] = maxv;
}
// preprocess last column
maxv = mat[N - 1][N - 1]; // Initialize max
for (int i = N - 2; i >= 0; i--)
{
if (mat[i][N - 1] > maxv)
maxv = mat[i][N - 1];
maxArr[i][N - 1] = maxv;
}
// preprocess rest of the matrix from bottom
for (int i = N-2; i >= 0; i--)
{
for (int j = N-2; j >= 0; j--)
{
// Update maxValue
if (maxArr[i+1][j+1] - mat[i][j] > maxValue)
maxValue = maxArr[i + 1][j + 1] - mat[i][j];
// set maxArr (i, j)
maxArr[i][j] = Math.max(mat[i][j],
Math.max(maxArr[i][j + 1],
maxArr[i + 1][j]) );
}
}
return maxValue;
}
// Driver code
public static void main (String[] args)
{
int N = 5;
int mat[][] = {
{ 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 }
};
System.out.print("Maximum Value is " +
findMaxValue(N,mat));
}
}
// Contributed by Prakriti Gupta
Python3
# An efficient method to find maximum value
# of mat[d] - ma[a][b] such that c > a and d > b
import sys
N = 5
# The function returns maximum value
# A(c,d) - A(a,b) over all choices of
# indexes such that both c > a and d > b.
def findMaxValue(mat):
# stores maximum value
maxValue = -sys.maxsize -1
# maxArr[i][j] stores max of elements
# in matrix from (i, j) to (N-1, N-1)
maxArr = [[0 for x in range(N)]
for y in range(N)]
# last element of maxArr will be
# same's as of the input matrix
maxArr[N - 1][N - 1] = mat[N - 1][N - 1]
# preprocess last row
maxv = mat[N - 1][N - 1]; # Initialize max
for j in range (N - 2, -1, -1):
if (mat[N - 1][j] > maxv):
maxv = mat[N - 1][j]
maxArr[N - 1][j] = maxv
# preprocess last column
maxv = mat[N - 1][N - 1] # Initialize max
for i in range (N - 2, -1, -1):
if (mat[i][N - 1] > maxv):
maxv = mat[i][N - 1]
maxArr[i][N - 1] = maxv
# preprocess rest of the matrix
# from bottom
for i in range (N - 2, -1, -1):
for j in range (N - 2, -1, -1):
# Update maxValue
if (maxArr[i + 1][j + 1] -
mat[i][j] > maxValue):
maxValue = (maxArr[i + 1][j + 1] -
mat[i][j])
# set maxArr (i, j)
maxArr[i][j] = max(mat[i][j],
max(maxArr[i][j + 1],
maxArr[i + 1][j]))
return maxValue
# Driver Code
mat = [[ 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 ]]
print ("Maximum Value is",
findMaxValue(mat))
# This code is contributed by iAyushRaj
C#
// An efficient method to find
// maximum value of mat1[d]
// - ma[a][b] such that c > a
// and d > b
using System;
class GFG {
// The function returns
// maximum value A(c,d) - A(a,b)
// over all choices of indexes
// such that both c > a
// and d > b.
static int findMaxValue(int N, int [,]mat)
{
//stores maximum value
int maxValue = int.MinValue;
// maxArr[i][j] stores max
// of elements in matrix
// from (i, j) to (N-1, N-1)
int [,]maxArr = new int[N, N];
// last element of maxArr
// will be same's as of
// the input matrix
maxArr[N - 1, N - 1] = mat[N - 1,N - 1];
// preprocess last row
// Initialize max
int maxv = mat[N - 1, N - 1];
for (int j = N - 2; j >= 0; j--)
{
if (mat[N - 1, j] > maxv)
maxv = mat[N - 1, j];
maxArr[N - 1, j] = maxv;
}
// preprocess last column
// Initialize max
maxv = mat[N - 1,N - 1];
for (int i = N - 2; i >= 0; i--)
{
if (mat[i, N - 1] > maxv)
maxv = mat[i,N - 1];
maxArr[i,N - 1] = maxv;
}
// preprocess rest of the
// matrix from bottom
for (int i = N - 2; i >= 0; i--)
{
for (int j = N - 2; j >= 0; j--)
{
// Update maxValue
if (maxArr[i + 1,j + 1] -
mat[i, j] > maxValue)
maxValue = maxArr[i + 1,j + 1] -
mat[i, j];
// set maxArr (i, j)
maxArr[i,j] = Math.Max(mat[i, j],
Math.Max(maxArr[i, j + 1],
maxArr[i + 1, j]) );
}
}
return maxValue;
}
// Driver code
public static void Main ()
{
int N = 5;
int [,]mat = {{ 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 }};
Console.Write("Maximum Value is " +
findMaxValue(N,mat));
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// An efficient method to find maximum value of mat1[d]
// - ma[a][b] such that c > a and d > b
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
function findMaxValue(N,mat)
{
// stores maximum value
let maxValue = Number.MIN_VALUE;
// maxArr[i][j] stores max of elements in matrix
// from (i, j) to (N-1, N-1)
let maxArr=new Array(N);
for(let i = 0; i < N; i++)
{
maxArr[i]=new Array(N);
}
// last element of maxArr will be same's as of
// the input matrix
maxArr[N - 1][N - 1] = mat[N - 1][N - 1];
// preprocess last row
let maxv = mat[N-1][N-1]; // Initialize max
for (let j = N - 2; j >= 0; j--)
{
if (mat[N - 1][j] > maxv)
maxv = mat[N - 1][j];
maxArr[N - 1][j] = maxv;
}
// preprocess last column
maxv = mat[N - 1][N - 1]; // Initialize max
for (let i = N - 2; i >= 0; i--)
{
if (mat[i][N - 1] > maxv)
maxv = mat[i][N - 1];
maxArr[i][N - 1] = maxv;
}
// preprocess rest of the matrix from bottom
for (let i = N-2; i >= 0; i--)
{
for (let j = N-2; j >= 0; j--)
{
// Update maxValue
if (maxArr[i+1][j+1] - mat[i][j] > maxValue)
maxValue = maxArr[i + 1][j + 1] - mat[i][j];
// set maxArr (i, j)
maxArr[i][j] = Math.max(mat[i][j],
Math.max(maxArr[i][j + 1],
maxArr[i + 1][j]) );
}
}
return maxValue;
}
// Driver code
let N = 5;
let mat = [[ 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 ]];
document.write("Maximum Value is " +
findMaxValue(N,mat));
// This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// An efficient method to find
// maximum value of mat[d] - ma[a][b]
// such that c > a and d > b
$N = 5;
// The function returns maximum
// value A(c,d) - A(a,b) over
// all choices of indexes such
// that both c > a and d > b.
function findMaxValue($mat)
{
global $N;
// stores maximum value
$maxValue = PHP_INT_MIN;
// maxArr[i][j] stores max
// of elements in matrix
// from (i, j) to (N-1, N-1)
$maxArr[$N][$N] = array();
// last element of maxArr
// will be same's as of
// the input matrix
$maxArr[$N - 1][$N - 1] = $mat[$N - 1][$N - 1];
// preprocess last row
$maxv = $mat[$N - 1][$N - 1]; // Initialize max
for ($j = $N - 2; $j >= 0; $j--)
{
if ($mat[$N - 1][$j] > $maxv)
$maxv = $mat[$N - 1][$j];
$maxArr[$N - 1][$j] = $maxv;
}
// preprocess last column
$maxv = $mat[$N - 1][$N - 1]; // Initialize max
for ($i = $N - 2; $i >= 0; $i--)
{
if ($mat[$i][$N - 1] > $maxv)
$maxv = $mat[$i][$N - 1];
$maxArr[$i][$N - 1] = $maxv;
}
// preprocess rest of the
// matrix from bottom
for ($i = $N - 2; $i >= 0; $i--)
{
for ($j = $N - 2; $j >= 0; $j--)
{
// Update maxValue
if ($maxArr[$i + 1][$j + 1] -
$mat[$i][$j] > $maxValue)
$maxValue = $maxArr[$i + 1][$j + 1] -
$mat[$i][$j];
// set maxArr (i, j)
$maxArr[$i][$j] = max($mat[$i][$j],
max($maxArr[$i][$j + 1],
$maxArr[$i + 1][$j]));
}
}
return $maxValue;
}
// Driver Code
$mat = array(array(1, 2, -1, -4, -20),
array(-8, -3, 4, 2, 1),
array(3, 8, 6, 1, 3),
array(-4, -1, 1, 7, -6),
array(0, -4, 10, -5, 1)
);
echo "Maximum Value is ".
findMaxValue($mat);
// This code is contributed
// by ChitraNayal
?>
OutputMaximum 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.
C++
// An optimal method to find maximum value of mat[c][d]
// - ma[a][b] such that c > a and d > b
#include <bits/stdc++.h>
using namespace std;
#define N 5
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
int findMaxValue(int mat[][N])
{
vector<int> temp1(N), temp2(N);
temp1[N - 1] = mat[N - 1][N - 1];
// Fill temp1
for (int j = N - 2; j >= 0; j--)
temp1[j] = max(temp1[j + 1], mat[N - 1][j]);
// stores maximum value
int maxValue = INT_MIN;
// Iterate over the remaining rows
for (int i = N - 2; i >= 0; i--) {
// Initialize the last element of temp2
temp2[N - 1] = max(temp1[N - 1], mat[i][N - 1]);
for (int j = N - 2; j >= 0; j--) {
// update temp2 and maxValue
maxValue
= max(maxValue, temp1[j + 1] - mat[i][j]);
temp2[j] = max(
{ mat[i][j], temp1[j], temp2[j + 1] });
}
// Set temp1 to temp2 for the next iteration
temp1 = temp2;
}
// Return the maximum value
return maxValue;
}
// Driver program to test above function
int main()
{
int 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 } };
cout << "Maximum Value is " << findMaxValue(mat);
return 0;
}
// This code is contributed by Tapesh(tapeshdua420)
Java
import java.util.Arrays;
public class Main {
static final int N = 5;
// The function returns the maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
static int findMaxValue(int[][] mat) {
int[] temp1 = new int[N];
int[] temp2 = new int[N];
temp1[N - 1] = mat[N - 1][N - 1];
// Fill temp1
for (int j = N - 2; j >= 0; j--) {
temp1[j] = Math.max(temp1[j + 1], mat[N - 1][j]);
}
// Stores the maximum value
int maxValue = Integer.MIN_VALUE;
// Iterate over the remaining rows
for (int i = N - 2; i >= 0; i--) {
// Initialize the last element of temp2
temp2[N - 1] = Math.max(temp1[N - 1], mat[i][N - 1]);
for (int j = N - 2; j >= 0; j--) {
// Update temp2 and maxValue
maxValue = Math.max(maxValue, temp1[j + 1] - mat[i][j]);
temp2[j] = Math.max(mat[i][j], Math.max(temp1[j], temp2[j + 1]));
}
// Set temp1 to temp2 for the next iteration
temp1 = Arrays.copyOf(temp2, temp2.length);
}
// Return the maximum value
return maxValue;
}
// Driver program to test the above function
public static void main(String[] args) {
int[][] mat = {
{ 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 }
};
System.out.println("Maximum Value is " + findMaxValue(mat));
}
}
Python3
def find_max_value(mat):
N = len(mat)
temp1 = [0] * N
temp2 = [0] * N
temp1[N - 1] = mat[N - 1][N - 1]
# Fill temp1
for j in range(N - 2, -1, -1):
temp1[j] = max(temp1[j + 1], mat[N - 1][j])
# Initialize the maximum value
max_value = float("-inf")
# Iterate over the remaining rows
for i in range(N - 2, -1, -1):
# Initialize the last element of temp2
temp2[N - 1] = max(temp1[N - 1], mat[i][N - 1])
for j in range(N - 2, -1, -1):
# Update temp2 and max_value
max_value = max(max_value, temp1[j + 1] - mat[i][j])
temp2[j] = max(mat[i][j], temp1[j], temp2[j + 1])
# Set temp1 to temp2 for the next iteration
temp1 = temp2
# Return the maximum value
return max_value
# Driver program to test the function
if __name__ == "__main__":
mat = [[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]]
print("Maximum Value is", find_max_value(mat))
# This code is contributed by shivamgupta0987654321
C#
using System;
class Program
{
const int N = 5;
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
static int FindMaxValue(int[,] mat)
{
int[] temp1 = new int[N];
int[] temp2 = new int[N];
temp1[N - 1] = mat[N - 1, N - 1];
// Fill temp1
for (int j = N - 2; j >= 0; j--)
temp1[j] = Math.Max(temp1[j + 1], mat[N - 1, j]);
// stores maximum value
int maxValue = int.MinValue;
// Iterate over the remaining rows
for (int i = N - 2; i >= 0; i--)
{
// Initialize the last element of temp2
temp2[N - 1] = Math.Max(temp1[N - 1], mat[i, N - 1]);
for (int j = N - 2; j >= 0; j--)
{
// update temp2 and maxValue
maxValue = Math.Max(maxValue, temp1[j + 1] - mat[i, j]);
temp2[j] = Math.Max(mat[i, j], Math.Max(temp1[j], temp2[j + 1]));
}
// Set temp1 to temp2 for the next iteration
temp1 = (int[])temp2.Clone();
}
// Return the maximum value
return maxValue;
}
// Driver program to test above function
static void Main()
{
int[,] mat = { { 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 } };
Console.WriteLine("Maximum Value is " + FindMaxValue(mat));
}
}
// This code is contributed by shivamgupta310570
JavaScript
// An optimal method to find maximum value of mat[c][d] - mat[a][b] such that c > a and d > b
const N = 5;
// The function returns the maximum value mat[c][d] - mat[a][b] over all choices of indexes such that both c > a and d > b.
function findMaxValue(mat) {
const temp1 = new Array(N);
const temp2 = new Array(N);
temp1[N - 1] = mat[N - 1][N - 1];
// Fill temp1
for (let j = N - 2; j >= 0; j--)
temp1[j] = Math.max(temp1[j + 1], mat[N - 1][j]);
// Stores the maximum value
let maxValue = Number.MIN_SAFE_INTEGER;
// Iterate over the remaining rows
for (let i = N - 2; i >= 0; i--) {
// Initialize the last element of temp2
temp2[N - 1] = Math.max(temp1[N - 1], mat[i][N - 1]);
for (let j = N - 2; j >= 0; j--) {
// Update temp2 and maxValue
maxValue = Math.max(maxValue, temp1[j + 1] - mat[i][j]);
temp2[j] = Math.max(mat[i][j], temp1[j], temp2[j + 1]);
}
// Set temp1 to temp2 for the next iteration
temp1.splice(0, N, ...temp2);
}
// Return the maximum value
return maxValue;
}
// Driver program to test the function
const mat = [
[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]
];
console.log("Maximum Value is", findMaxValue(mat));
OutputMaximum 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.
Similar Reads
Pair with given sum in matrix
Given a NxM matrix and a sum S. The task is to check if a pair with given Sum exists in the matrix or not. Examples: Input: mat[N][M] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; sum = 31 Output: YES Input: mat[N][M] = {{1, 2, 3, 4}, {5, 6, 7, 8}}; sum = 150 Output: NO Approach
6 min read
Count inversion pairs in a matrix
Given a matrix A of size NxN, we need to find the number of inversion pairs in it. Inversion count in a matrix is defined as the number of pairs satisfying the following conditions : x1 ? x2y1 ? y2A[x2][y2] < A[x1][y1] Constraints : 1 ? Ai,j ? 1091 ? N ? 103 Examples: For simplicity, let's take a
14 min read
Find unique elements in a matrix
Given a matrix mat[][] having n rows and m columns. The task is to find unique elements in the matrix i.e., those elements which are not repeated in the matrix or those elements whose frequency is 1. Examples: Input: mat[][] = [[2, 1, 4, 3], [1, 2, 3, 2], [3, 6, 2, 3], [5, 2, 5, 3]]Output: 4 6Input:
5 min read
Search element in a sorted matrix
Given a sorted matrix mat[][] of size nxm and an element x, the task is to find if x is present in the matrix or not. Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row i, where 1 <= i <= n-1, the first element of row i is greater than or equal
13 min read
Pair with maximum difference in a Matrix
Given a NxM matrix with N rows and M columns of positive integers. The task is to find the pair with the maximum difference in the given matrix. Note: Pairs at positions (a, b) and (b, a) are considered equivalent. Examples: Input : mat[N][M] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14,
5 min read
Search in a Matrix or 2D Array
Given a matrix mat[n][m] and an element target. return true if the target is present in the matrix, else return false. Examples: Input : mat[][] = { {10, 51, 9}, {14, 20, 21}, {30, 24, 43} }target = 14Output: Found Input : mat[][] = {{31, 5, 9, 11}, {14, 7, 21, 26}, {30, 4, 43, 50} }target = 42Outpu
4 min read
Pair with maximum sum in a Matrix
Given a NxM matrix with N rows and M columns of positive integers. The task is to find the sum of pair with maximum sum in the matrix. Examples: Input : mat[N][M] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output : 41 Pair (25, 16) has the maximum sum Input : mat[N][M] = {{1,
7 min read
Maximize matrix as per given condition
you are given an N*N matrix, where each element of the matrix lies in the range 0 to M. You can apply the below operation on the matrix any number of times: Choose any two consecutive elementsIncrement one of them by 1 and decrease the other by 1 Note: The elements should remain within the range of
9 min read
Find the Peak Element in a 2D Array/Matrix
Given a 2D Array/Matrix mat[][], the task is to find the Peak element.An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. A peak element is not necessarily the overall maximal element. It only needs to be greater than existing adjacent More
12 min read
Program to find all types of Matrix
Given the dimension of the matrix R(rows) * C(column) the task is to find which type of matrix is represented by the given dimension. Examples: Input : R = 1 C = 0Output : Row Matrix Input : R = 4 C = 5Output : Horizontal Matrix Row Matrix : When R = 1 and C = 0 then the matrix represent Row Matrix
5 min read