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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code