Maximum Matrix Sum - Problem
You are given an n ร n integer matrix. Your mission is to maximize the sum of all elements in the matrix using a special operation.
The Operation: Choose any two adjacent elements in the matrix and multiply both by -1. Two elements are adjacent if they share a border (horizontally or vertically connected).
You can perform this operation any number of times, including zero times. Your goal is to find the maximum possible sum of all matrix elements after applying operations optimally.
Example: In matrix [[-1, 0, 1], [0, -1, 0], [1, 0, -1]], you can flip adjacent negative values to make them positive, maximizing the total sum.
Input & Output
example_1.py โ Basic 2x2 Matrix
$
Input:
matrix = [[1,-1],[-1,1]]
โบ
Output:
4
๐ก Note:
We can flip the pair (-1,-1) to make them both positive, or flip (1,-1) and (-1,1) to achieve sum of 4. All elements become positive: [[1,1],[1,1]]
example_2.py โ 3x3 with Odd Negatives
$
Input:
matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
โบ
Output:
16
๐ก Note:
We have 3 negative values (odd count). We can pair -1 and -2, but -3 must remain negative since we have odd count. Sum = 1+2+3+1+2+3+1+2-3 = 12. But optimally, we keep the smallest absolute value (-1) negative: 16.
example_3.py โ All Positive
$
Input:
matrix = [[2,3],[5,4]]
โบ
Output:
14
๐ก Note:
All elements are already positive, so no operations needed. Maximum sum is 2+3+5+4 = 14.
Constraints
- n == matrix.length == matrix[i].length
- 1 โค n โค 250
- -105 โค matrix[i][j] โค 105
Visualization
Tap to expand
Understanding the Visualization
1
Analyze the Board
Count how many black squares (negatives) you have and identify the lightest gray square (minimum absolute value)
2
Pair Up Negatives
Each pair of black squares can be converted to white squares through adjacent flips
3
Handle the Remainder
If you have an odd number of black squares, one must remain black - choose the one that hurts your score the least
Key Takeaway
๐ฏ Key Insight: Since each operation flips exactly two adjacent elements, we can always pair up negatives to make them positive. If we have an odd number of negatives, exactly one must remain negative - choose the one with smallest absolute value to minimize the loss.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code