Maximum Matrix Sum - Problem

You are given an n x n integer matrix. You can perform the following operation any number of times:

Choose any two adjacent elements of the matrix and multiply each of them by -1.

Two elements are considered adjacent if and only if they share a border (horizontally or vertically).

Your goal is to maximize the summation of all matrix elements. Return the maximum possible sum after performing the operations.

Input & Output

Example 1 — Even Negatives
$ Input: matrix = [[1,-1],[-1,1]]
Output: 4
💡 Note: We have 2 negatives (even count). We can make all elements positive: flip (-1,1) and (-1,-1) → all become positive. Sum = 1+1+1+1 = 4
Example 2 — Odd Negatives
$ Input: matrix = [[1,2,3],[-1,-2,-3]]
Output: 10
💡 Note: We have 3 negatives (odd count). Sum of absolute values = 1+2+3+1+2+3 = 12. Since we have odd negatives, we must keep one negative (the one with smallest absolute value = 1). Result = 12 - 2×1 = 10.
Example 3 — All Positive
$ Input: matrix = [[2,3],[5,4]]
Output: 14
💡 Note: All elements are already positive. No operations needed. Sum = 2+3+5+4 = 14

Constraints

  • n == matrix.length == matrix[i].length
  • 1 ≤ n ≤ 250
  • -105 ≤ matrix[i][j] ≤ 105

Visualization

Tap to expand
Maximum Matrix Sum INPUT 2x2 Integer Matrix 1 -1 -1 1 Adjacent pairs can flip matrix = [[1,-1],[-1,1]] 2 negative values Sum of |values| = 4 Negative count = 2 (even) ALGORITHM STEPS 1 Count Negatives Track negative count 2 Sum Absolute Values |1|+|-1|+|-1|+|1| = 4 3 Find Minimum |value| min = 1 4 Check Parity If odd negatives: sum - 2*min Decision Logic: negCount % 2 == 0? YES: return sum = 4 2 % 2 == 0 --> sum = 4 All negatives can be eliminated FINAL RESULT Optimal Matrix State 1 1 1 1 1 + 1 + 1 + 1 = 4 Output: 4 OK - Maximum Sum! Key Insight: Adjacent flips can move negatives anywhere. If negative count is EVEN, all can cancel out. If ODD, one negative remains - put it on smallest absolute value. Result: sum(|all|) - 2*min(|all|) Time: O(n^2) | Space: O(1) | Greedy Mathematical Approach TutorialsPoint - Maximum Matrix Sum | Greedy - Mathematical Insight
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen