710013. Maximum difference between pair in a matrix

Hard

Maximum difference between pair in a matrix

Summary

Given an m x n matrix, find the maximum difference between the sum of two elements, where one element is from each row. The problem requires us to maximize the difference by selecting the smallest and largest elements from different rows.

Detailed Explanation

To solve this problem, we need to iterate through each row in the matrix and keep track of the minimum and maximum values encountered so far. We will also maintain two variables to store the minimum and maximum differences seen till now. The maximum difference is updated whenever a larger difference is found between the current minimum and maximum values.

Here's a step-by-step breakdown of the solution:

  1. Initialize min_val and max_val to represent the smallest and largest elements in the first row, respectively.
  2. Iterate through each row in the matrix (m times):
    • Update min_val if the current element is smaller than min_val.
    • Update max_val if the current element is larger than max_val.
  3. Calculate the maximum difference (diff) between the sum of min_val and the sum of max_val. This represents the maximum difference that can be achieved by selecting one element from each row.
  4. Return the calculated diff.

Time Complexity: O(m * n), where m is the number of rows and n is the number of columns in the matrix.

Space Complexity: O(1), as we only use a constant amount of space to store the minimum and maximum values.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxDifference(int[][] matrix) {
    int m = matrix.length;
    int n = matrix[0].length;
    int min_val = Integer.MAX_VALUE, max_val = Integer.MIN_VALUE;
    int diff = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (matrix[i][j] < min_val) {
                min_val = matrix[i][j];
            }
            if (matrix[i][j] > max_val) {
                max_val = matrix[i][j];
            }
        }
    }

    diff = max_val - min_val;

    return diff;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.