- Interview Questions
- /
- Problems
- /
- Maximum Matrix Sum
Maximum Matrix Sum
Flip the signs of adjacent pairs in a square matrix as often as you like to maximize its total. A parity argument: only whether the count of negatives is odd matters. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given an n × n integer matrix matrix. In one move you may pick any two cells that are adjacent (sharing an edge, horizontally or vertically) and multiply both of them by -1.
You can make as many moves as you like. Return the largest possible sum of all the matrix's elements.
Example 1
- Input
- matrix = [[2, -3], [-4, 5]]
- Output
- 14
Flip the top row pair (2 and -3) to get [[-2, 3], [-4, 5]], then the left column pair (-2 and -4) to get [[2, 3], [4, 5]]. The sum is 14.
Example 2
- Input
- matrix = [[1, -2, 3], [4, 5, 6], [7, 8, 9]]
- Output
- 43
There is one negative, and every move keeps the count of negatives odd or even as it was, so one value must stay negative. Make it the 1: the absolute values sum to 45, and 45 - 2 × 1 = 43.
Example 3
- Input
- matrix = [[-5, 0], [3, -1]]
- Output
- 9
Two negatives can both be made positive: 5 + 0 + 3 + 1 = 9.
Constraints
- n == matrix.length == matrix[i].length
- 2 ≤ n ≤ 250
- -10⁵ ≤ matrix[i][j] ≤ 10⁵
Practice
Runs 13 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Maximum Matrix Sum in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Maximum Matrix Sum
Pattern: Parity invariant (greedy)
Simulating moves is a dead end; the state space is huge. Instead, ask what a move can and cannot change.
What it can do: by flipping a chain of adjacent pairs along a path, you flip the two endpoints and every cell in between twice, which leaves the middle unchanged. So you can flip the signs of any two cells, not just neighbors. That means negatives can be paired up and cancelled anywhere in the grid.
What it can't do: each move flips two signs, so the number of negative values changes by -2, 0, or +2. Its parity never changes (ignoring zeros, which have no sign).
Put together: if the count of negatives is even, every value can end up non-negative and the answer is the sum of absolute values. If it is odd, exactly one value must stay negative, so pick the one with the smallest absolute value and subtract it twice. A zero in the grid makes this free, because the smallest absolute value is 0.
Approach 1: Search over flip states
Treat each matrix as a state and run a BFS or DFS over all reachable sign patterns, tracking the best sum. It works for a 2 × 2 grid and nothing larger, since there are up to 2^(n²) patterns.
Time O(2^(n²)) · Space O(2^(n²))
Approach 2: Sort absolute values
Collect absolute values, sort them, sum them, and if the negative count is odd subtract twice the first one. Correct, but sorting is unnecessary when you only need the minimum.
Time O(n² log n) · Space O(n²)
Approach 3: One pass: sum, count, minimum
Scan every cell once, tracking:
total, the sum of absolute values.negatives, how many values are below zero.minAbs, the smallest absolute value.
Return total if negatives is even, otherwise total - 2 * minAbs.
Time O(n²) · Space O(1)
| Approach | Time | Space |
|---|---|---|
| Search over flip states | O(2^(n²)) | O(2^(n²)) |
| Sort absolute values | O(n² log n) | O(n²) |
| One pass: sum, count, minimum | O(n²) | O(1) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Maximum Matrix Sum solution in Python
def max_matrix_sum(matrix: list[list[int]]) -> int:
total = 0
negatives = 0
min_abs = float("inf")
for row in matrix:
for v in row:
total += abs(v)
if v < 0:
negatives += 1
min_abs = min(min_abs, abs(v))
# Negatives can be cancelled in pairs; with an odd count, one value stays negative.
return total if negatives % 2 == 0 else total - 2 * min_absMaximum Matrix Sum solution in JavaScript
function maxMatrixSum(matrix) {
let total = 0;
let negatives = 0;
let minAbs = Infinity;
for (const row of matrix) {
for (const v of row) {
total += Math.abs(v);
if (v < 0) negatives++;
minAbs = Math.min(minAbs, Math.abs(v));
}
}
// Negatives can be cancelled in pairs; with an odd count, one value stays negative.
return negatives % 2 === 0 ? total : total - 2 * minAbs;
}Common mistakes
- Thinking only literal neighbors can be paired. A chain of moves flips any two cells.
- Choosing the smallest negative value to leave behind instead of the smallest absolute value anywhere, which may be positive.
- Forgetting zeros. A zero makes minAbs 0, so an odd count costs nothing.
- Subtracting minAbs once instead of twice. The value goes from +x in the total to -x.
What interviewers look for
Interviewers are listening for two claims, each with a one-line proof: "any two cells can be flipped together, via a path of moves" and "the parity of the negative count never changes." Say both before writing code; the code is then four lines.
Try a 2 × 2 example by hand to show the path argument, then point out the zero case explicitly.
Follow-up questions
What if a move flipped a single cell instead of a pair?
Then parity no longer constrains anything, and the answer is always the sum of absolute values.
What if a move flipped an entire row or column?
That is a harder problem. Row and column flips commute and each is its own inverse, so you choose a subset of rows to flip, and then each column's best choice is independent. Brute force over row subsets is O(2ⁿ · n²); there is no simple parity shortcut.
Does the matrix need to be square, or even a grid?
No. The argument only needs the cells to form a connected graph under the adjacency rule, so it holds for any rectangular grid or any connected graph of values.
Companies that ask Maximum Matrix Sum
Maximum Matrix Sum is tagged by 92 companies in our interview dataset. The score shows how often it comes up at each company.
- Cytokinetics100%
- Vanta100%
- CVS Health100%
- Lacework94%
- Unanet90%
- Glance87%
- Fdm Group87%
- One Medical85%
- Clear85%
- Rally Health84%
- Peraton82%
- Walmart80%
- Varonis79%
- Front78%
- Liberty It77%
- Wex77%
- Olympus77%
- Honeywell76.7%
- Bandwidth76%
- Gopuff76%
- Lumentum76%
- Sap Concur76%
- Caterpillar75%
- Brillio75%
and 68 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required