Find pair with maximum difference in any column of a Matrix in C++

C++Server Side ProgrammingProgramming

Suppose we have one matrix or order NxN. We have to find a pair of elements which forms maximum difference from any column of the matrix. So if the matrix is like −

123
535
967

So output will be 8. As the pair is (1, 9) from column 0.

The idea is simple, we have to simply find the difference between max and min elements of each column. Then return max difference.

Example

#include<iostream>
#define N 5
using namespace std;
int maxVal(int x, int y){
   return (x > y) ? x : y;
}
int minVal(int x, int y){
   return (x > y) ? y : x;
}
int colMaxDiff(int mat[N][N]) {
   int diff = INT_MIN;
   for (int i = 0; i < N; i++) {
      int max_val = mat[0][i], min_val = mat[0][i];
      for (int j = 1; j < N; j++) {
         max_val = maxVal(max_val, mat[j][i]);
         min_val = minVal(min_val, mat[j][i]);
      }
      diff = maxVal(diff, max_val - min_val);
   }
   return diff;
}
int main() {
   int mat[N][N] = {{ 1, 2, 3, 4, 5 }, { 5, 3, 5, 4, 0 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 },
{ 9, 7, 12, 4, 3 },};
   cout << "Max difference : " << colMaxDiff(mat) << endl;
}

Output

Max difference : 12
raja
Published on 18-Dec-2019 17:19:11
Advertisements