 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find pair with maximum difference in any column of a Matrix in C++
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 −
| 1 | 2 | 3 | 
| 5 | 3 | 5 | 
| 9 | 6 | 7 | 
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
Advertisements
 