Maximum Matrix Sum (LeetCode 1975): Solution and Explanation

Medium
Array
Greedy
Matrix

In an n x n matrix you may flip the signs of any two adjacent cells as often as you like. Return the largest sum the matrix can reach.

Intuition

Try the operation on a path of cells. Flipping cells 1 and 2, then 2 and 3, flips cell 2 twice, so only cells 1 and 3 change. Repeating along any path flips just its two endpoints. That means you can flip the signs of any two cells in the matrix, not only adjacent ones.

So the only question is which minus signs can be removed. Each operation changes the number of negatives by -2, 0 or +2, so the parity of that count never changes.

With an even number of negatives, pair them up and flip each pair: every cell becomes non-negative and the answer is the sum of absolute values.

With an odd number, one minus sign always survives. You can move it onto any cell, so put it on the cell with the smallest absolute value. It costs 2 * smallest compared with the all-positive sum. If a zero exists the cost is zero.

Approach: Count negatives and track the smallest absolute value

  1. Scan every cell once.
  2. Add abs(x) to total.
  3. If x < 0, increase neg.
  4. Keep smallest = min(smallest, abs(x)).
  5. If neg is odd, subtract 2 * smallest from total.
  6. Return total, using a 64-bit integer because it can reach 250 * 250 * 10^5.

Step-by-step example

matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
  1. The absolute values sum to 6 + 6 + 6 = 18.
  2. There are 3 negatives: -1, -2 and -3. That count is odd.
  3. The smallest absolute value is 1.
  4. Two of the minus signs cancel as a pair; the third stays and is moved onto a cell holding 1.
  5. total = 18 - 2 * 1 = 16.

Code: Python, Java, C++

1class Solution:
2    def maxMatrixSum(self, matrix: List[List[int]]) -> int:
3        total = 0
4        neg = 0
5        smallest = float('inf')
6        for row in matrix:
7            for x in row:
8                total += abs(x)
9                if x < 0:
10                    neg += 1
11                smallest = min(smallest, abs(x))
12        if neg % 2 == 1:
13            total -= 2 * smallest
14        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Every cell is visited once with constant work.

Space

O(1)

Only the running total, the negative count and the smallest absolute value are stored.

Other approaches

Sort all absolute values (time O(n^2 log n), space O(n^2))

Collect the absolute values, sort them, and subtract twice the first one when the negative count is odd. It gives the same answer with extra time and memory.

Common mistakes

  • Thinking only adjacent pairs can be flipped. Chaining operations flips any two cells.
  • Subtracting the smallest negative value instead of the smallest absolute value over all cells. The leftover sign can be moved onto a positive cell or onto a zero.
  • Subtracting smallest once instead of twice. The cell goes from +smallest to -smallest.
  • Using a 32-bit integer for the sum. It can reach 6.25 * 10^9.

Frequently asked questions

Why does a zero make the answer the full sum of absolute values?

The leftover minus sign can be moved onto the zero, and -0 is 0, so nothing is lost.

Why can the parity of negatives never change?

One operation flips two cells. Each flip changes the count by +1 or -1, so together they change it by -2, 0 or +2.

Does the matrix need to be square?

No. The argument only needs every cell to be reachable along a path of adjacent cells, which holds for any rectangular grid.