Maximum Matrix Sum (LeetCode 1975): Solution and Explanation
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
- Scan every cell once.
- Add
abs(x)tototal. - If
x < 0, increaseneg. - Keep
smallest = min(smallest, abs(x)). - If
negis odd, subtract2 * smallestfromtotal. - 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]]
- The absolute values sum to 6 + 6 + 6 = 18.
- There are 3 negatives: -1, -2 and -3. That count is odd.
- The smallest absolute value is 1.
- Two of the minus signs cancel as a pair; the third stays and is moved onto a cell holding 1.
- 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 total1class Solution {
2 public long maxMatrixSum(int[][] matrix) {
3 long total = 0;
4 int neg = 0;
5 int smallest = Integer.MAX_VALUE;
6 for (int[] row : matrix) {
7 for (int x : row) {
8 total += Math.abs(x);
9 if (x < 0) {
10 neg++;
11 }
12 smallest = Math.min(smallest, Math.abs(x));
13 }
14 }
15 if (neg % 2 == 1) {
16 total -= 2L * smallest;
17 }
18 return total;
19 }
20}1class Solution {
2public:
3 long long maxMatrixSum(vector<vector<int>>& matrix) {
4 long long total = 0;
5 int neg = 0;
6 int smallest = INT_MAX;
7 for (auto& row : matrix) {
8 for (int x : row) {
9 total += abs(x);
10 if (x < 0) {
11 neg++;
12 }
13 smallest = min(smallest, abs(x));
14 }
15 }
16 if (neg % 2 == 1) {
17 total -= 2LL * smallest;
18 }
19 return total;
20 }
21};Time and space complexity
O(n^2)
Every cell is visited once with constant work.
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
smallestonce 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.