2089. Maximum Matrix Sum
My accepted Python solution to LeetCode problem 2089, Maximum Matrix Sum, running in 81ms.
- Difficulty: Medium
- Python
- Runtime 81ms
- Memory 26.8MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 81ms, memory 26.8MB, accepted 2025-12-29.
class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
# Key insight: We can always make all values positive except possibly one
# If odd number of negatives, we keep the smallest absolute value negative
# Time: O(n^2), Space: O(1)
total = 0
min_abs = float('inf')
neg_count = 0
for row in matrix:
for val in row:
total += abs(val)
min_abs = min(min_abs, abs(val))
if val < 0:
neg_count += 1
# If odd number of negatives, we must keep one value negative
if neg_count % 2 == 1:
total -= 2 * min_abs
return total