Maximum Matrix Sum — LeetCode 1975 Python Solution
MediumGreedyArrayMatrix
- Problem
- #1975
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an n x n integer matrix. You can do the following operation any number of times: Choose any two adjacent elements of matrix and multiply each of them by -1.
Example
- Input
- matrix = [[1,-1],[-1,1]]
- Output
- 4
- Explanation
- We can follow the following steps to reach sum equals 4:
Python solution
Python
class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
mi = inf
s = cnt = 0
for row in matrix:
for x in row:
cnt += x < 0
y = abs(x)
mi = min(mi, y)
s += y
return s if cnt % 2 == 0 else s - mi * 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m and n are the number of rows and columns of the matrix, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1975. Maximum Matrix Sum is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
LeetCode 807Max Increase to Keep City SkylineMediumLeetCode 861Score After Flipping MatrixMediumLeetCode 1253Reconstruct a 2-Row Binary MatrixMediumLeetCode 1536Minimum Swaps to Arrange a Binary GridMediumLeetCode 1605Find Valid Matrix Given Row and Column SumsMediumLeetCode 1727Largest Submatrix With RearrangementsMedium
Frequently asked questions
- How hard is LeetCode 1975. Maximum Matrix Sum?
- LeetCode 1975. Maximum Matrix Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1975. Maximum Matrix Sum?
- The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of the matrix, respectively.
- What is the space complexity of LeetCode 1975. Maximum Matrix Sum?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1975. Maximum Matrix Sum cover?
- LeetCode 1975. Maximum Matrix Sum is tagged Greedy, Array and Matrix on LeetCode.