The Wayback Machine - https://web.archive.org/web/20240707142100/https://www.geeksforgeeks.org/find-pair-with-maximum-difference-in-any-column-of-a-matrix/
Open In App

Find pair with maximum difference in any column of a Matrix

Last Updated : 01 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a N*N matrix of positive integers. The task is to find the maximum difference between any pair of elements in any column of the matrix.

Examples: 

Input : 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 },
    };
Output : Max difference : 12
5th column has the pair with max difference
(0, 12)

Input : mat[N][N] = {
        { 1, 2, 3 },
        { 5, 3, 5 },
        { 9, 6, 7 }
    };
Output : Max difference : 8 

The idea is to observe that the pair with a maximum difference in any column is the difference between the maximum and minimum element of that column. Now traverse the matrix column-wise. Find the difference between the max and min elements of every column and return the maximum difference.

Below is the implementation of the above approach:  

C++




// C++ program to find column with
// max difference of any pair of elements
#include <bits/stdc++.h>
using namespace std;
 
#define N 5 // No of rows and column
 
// Function to find the column with max difference
int colMaxDiff(int mat[N][N])
{
    int max_diff = INT_MIN;
 
    // Traverse matrix column wise
    for (int i = 0; i < N; i++) {
 
        // Insert elements of column to vector
        int max_val = mat[0][i], min_val = mat[0][i];
        for (int j = 1; j < N; j++) {
            max_val = max(max_val, mat[j][i]);
            min_val = min(min_val, mat[j][i]);
        }
 
        // calculating difference between maximum and
        // minimum
        max_diff = max(max_diff, max_val - min_val);
    }
 
    return max_diff;
}
 
// driver code
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;
 
    return 0;
}


Java




// Java program to find column with
// max difference of any pair of elements
 
public class GOC1 {
 
    static int N = 5; // No of rows and column
 
    // Function to find the column with max difference
    static int colMaxDiff(int mat[][]) {
        int max_diff = Integer.MIN_VALUE;
 
        // Traverse matrix column wise
        for (int i = 0; i < N; i++) {
 
            // Insert elements of column to vector
            int max_val = mat[0][i], min_val = mat[0][i];
            for (int j = 1; j < N; j++) {
                max_val = Math.max(max_val, mat[j][i]);
                min_val = Math.min(min_val, mat[j][i]);
            }
 
            // calculating difference between maximum and
            // minimum
            max_diff = Math.max(max_diff, max_val - min_val);
        }
 
        return max_diff;
    }
 
    // Driver Code
    public static void main(String args[]) {
        int mat[][] = {
                { 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 },
            };
           
        System.out.println("Max difference : "+colMaxDiff(mat));
    }
}


Python3




# Python3 program to find column with
# max difference of any pair of elements
 
N = 5 # No of rows and column
 
# Function to find the column
# with max difference
def colMaxDiff(mat):
 
    max_diff = 0
 
    # Traverse matrix column wise
    for i in range (N):
 
        # Insert elements of column
        # to vector
        max_val = mat[0][i]
        min_val = mat[0][i]
        for j in range (1, N) :
            max_val = max(max_val, mat[j][i])
            min_val = min(min_val, mat[j][i])
 
        # calculating difference between
        # maximum and minimum
        max_diff = max(max_diff, max_val -
                                 min_val)
 
    return max_diff
 
# Driver Code
if __name__ == "__main__":
    mat = [[ 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 ]]
 
    print ("Max difference :", colMaxDiff(mat))
 
# This code is contributed by ita_c


C#




// C# program to find column 
// with max difference of
// any pair of elements
using System;
 
class GFG
{
 
static int N = 5; // No of rows and column
 
// Function to find the column
// with max difference
static int colMaxDiff(int [,]mat)
{
    int max_diff = int.MinValue;
 
    // Traverse matrix column wise
    for (int i = 0; i < N; i++)
    {
 
        // Insert elements of column
        // to vector
        int max_val = mat[0, i],
            min_val = mat[0, i];
        for (int j = 1; j < N; j++)
        {
            max_val = Math.Max(max_val,
                               mat[j, i]);
            min_val = Math.Min(min_val,
                               mat[j, i]);
        }
 
        // calculating difference between
        // maximum and minimum
        max_diff = Math.Max(max_diff,
                            max_val - min_val);
    }
 
    return max_diff;
}
 
// Driver Code
public static void Main()
{
    int [,]mat = { { 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 }};
         
    Console.WriteLine("Max difference : " +
                          colMaxDiff(mat));
}
}
 
// This code is contributed
// by Subhadeep


PHP




<?php
// PHP program to find column with
// max difference of any pair of elements
 
// Function to find the column with max difference
function colMaxDiff($mat)
{
    $N = 5;
    $max_diff = PHP_INT_MIN;
 
    // Traverse matrix column wise
    for ($i = 0; $i < $N; $i++)
    {
 
        // Insert elements of column to vector
        $max_val = $mat[0][$i]; $min_val = $mat[0][$i];
        for ($j = 1; $j < $N; $j++)
        {
            $max_val = max($max_val, $mat[$j][$i]);
            $min_val = min($min_val, $mat[$j][$i]);
        }
 
        // calculating difference between maximum and
        // minimum
        $max_diff = max($max_diff, $max_val - $min_val);
    }
 
    return $max_diff;
}
 
// driver code
$mat = array(array( 1, 2, 3, 4, 5 ),
             array(5, 3, 5, 4, 0 ),
             array(5, 6, 7, 8, 9 ),
             array(0, 6, 3, 4, 12 ),
             array(9, 7, 12, 4, 3 ));
 
echo "Max difference : " .
      colMaxDiff($mat) . "\n";
 
// This code is contributed
// by Akanksha Rai


Javascript




<script>
// Javascript program to find column with
// max difference of any pair of elements
     
    let N = 5; // No of rows and column
     
    // Function to find the column with max difference
    function colMaxDiff(mat)
    {
        let max_diff = Number.MIN_VALUE;
   
        // Traverse matrix column wise
        for (let i = 0; i < N; i++) {
   
            // Insert elements of column to vector
            let max_val = mat[0][i], min_val = mat[0][i];
            for (let j = 1; j < N; j++) {
                max_val = Math.max(max_val, mat[j][i]);
                min_val = Math.min(min_val, mat[j][i]);
            }
   
            // calculating difference between maximum and
            // minimum
            max_diff = Math.max(max_diff, max_val - min_val);
        }
   
        return max_diff;
    }
     
     // Driver Code
    let mat = [[ 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 ]];
     
    document.write("Max difference :"+ colMaxDiff(mat))
 
 
// This code is contributed by rag2127
</script>


Output

Max difference : 12

Time Complexity: O(n^2)
Auxiliary Space: O(1)



Similar Reads

Find row and column pair in given Matrix with equal row and column sum
Given a matrix Mat of size N x M, the task is to find all the pairs of rows and columns where the sum of elements in the row is equal to the sum of elements in the columns. Examples: Input: M = {{1, 2, 2}, {1, 5, 6}, {3, 8, 9}}Output: {{1, 1}}Explanation: The sum of elements of rows and columns of matrix M are: C = 1C = 2C = 3Sum of RowsR = 11225R
8 min read
Pair with given product | Set 1 (Find if any pair exists)
Given an array of distinct elements and a number x, find if there is a pair with a product equal to x. Examples : Input : arr[] = {10, 20, 9, 40}; int x = 400;Output : YesInput : arr[] = {10, 20, 9, 40}; int x = 190;Output : NoInput : arr[] = {-10, 20, 9, -40}; int x = 400;Output : YesInput : arr[] = {-10, 20, 9, 40}; int x = -400;Output : YesInput
15+ min read
Maximum sum of any submatrix of a Matrix which is sorted row-wise and column-wise
Given a matrix mat[][] whose elements are sorted both row-wise and column-wise. The task is to find the maximum sum of any submatrix from the given matrix mat[][]. Examples: Input: mat[][] = { {-6, -4, -1}, {-3, 2, 4}, {2, 5, 8}} Output: 19 Explanation: The largest submatrix is given by: 2 4 5 8Input: mat[][] = { {-4, -3}, {-2, -1} } Output: -1 Exp
10 min read
Minimize rows to be made zero for last column sum to be at most any one column
Given an N * M matrix mat[][] consisting of non-negative integers. In one operation, select any row and change all elements to 0. The task is to find the minimum number of operations required such that the sum of elements in the Mth column is less than or equal to the sum of elements in jth column for at least one 'j' ( where 1 â‰Ī 'j' â‰Ī 'M'-1). Exam
15+ min read
Find product of GCDs of all possible row-column pair of given Matrix
Given a matrix of size N*M, the task is to find the product of all possible pairs of (i, j) where i and j are the row number and column number respectively. Note: Since the answer can be very large output the answer modulo 1000000007. Examples: Input: N = 5, M = 6Output: 5760Explanation: The values of GCD of each possible pair 1111111212121 1311312
12 min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Queries to check if any pair exists in an array having values at most equal to the given pair
Given a vector of pairs arr[] and Q queries in the form of pairs in an array Queries[], the task for each query is to check if there exists any pair with both the values smaller than those in the pair of the current query. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[][] = {{3, 5}, {2, 7}, {2, 3}, {4, 9}}, Quer
12 min read
Find pair of rows in a binary matrix that has maximum bit difference
Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has maximum bit difference Examples: Input: mat[][] = {{1, 1, 1, 1}, {1, 1, 0, 1}, {0, 0, 0, 0}}; Output : (1, 3) Bit difference between row numbers 1 and 3 is maximum with value 4. Bit difference between 1 and 2 is 1 and between 2 and 3 is 3. Input: mat[][] = {{1
15 min read
Minimize product of first 2^K–1 Natural Numbers by swapping bits for any pair any number of times
Given a positive integer K, the task is to minimize the positive product of the first (2K - 1) Natural Numbers by swapping the bits at the corresponding position of any two numbers any number of times. Examples: Input: K = 3Output: 1512Explanation: The original product is 5040. The given array in binary notation is {001, 010, 011, 100, 101, 110, 11
5 min read
Smallest number that can replace all -1s in an array such that maximum absolute difference between any pair of adjacent elements is minimum
Given an array arr[] consisting of N positive integers and some elements as -1, the task is to find the smallest number, say K, such that replacing all -1s in the array by K minimizes the maximum absolute difference between any pair of adjacent elements. Examples: Input: arr[] = {-1, 10, -1, 12, -1}Output: 11Explanation:Consider the value of K as 1
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg