Find a specific pair in Matrix in C++

C++Server Side ProgrammingProgramming

Suppose there is an n x n matrix mat of integers. we have to find maximum value of mat(c, d) - mat(a, b) over all choices of indexes. Here we have to keep in mind that c > a and d > b. So if the matrix is like −


12-1-4-20
-8-3421
38613
-4-117-6
0-410-51

The output will be 18. This is because mat[4, 2] - mat[1, 0] = 18 has maximum difference.

To solve this we will preprocess 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. Then we will return the max value.

Example

 Live Demo

#include<iostream>
#define N 5
using namespace std;
int findMaxValue(int matrix[][N]) {
   int maxValue = -99999;
   int arr_max[N][N];
   arr_max[N-1][N-1] = matrix[N-1][N-1];
   int max_val = matrix[N-1][N-1];
   for (int j = N - 2; j >= 0; j--) {
      if (matrix[N-1][j] > max_val)
      max_val = matrix[N - 1][j];
      arr_max[N-1][j] = max_val;
   }
   max_val = matrix[N - 1][N - 1];
   for (int i = N - 2; i >= 0; i--) {
      if (matrix[i][N - 1] > max_val)
      max_val = matrix[i][N - 1];
      arr_max[i][N - 1] = max_val;
   }
   for (int i = N-2; i >= 0; i--) {
      for (int j = N-2; j >= 0; j--) {
         if (arr_max[i+1][j+1] - matrix[i][j] > maxValue)
         maxValue = arr_max[i + 1][j + 1] - matrix[i][j];
         arr_max[i][j] = max(matrix[i][j],max(arr_max[i][j + 1],arr_max[i + 1][j]) );
      }
   }
   return maxValue;
}
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);
}

Output

Maximum Value is 18
raja
Published on 03-Jan-2020 09:46:04
Advertisements