Maximum Matrix Sum — LeetCode 1975 Python Solution

MediumGreedyArrayMatrix
Problem
#1975
Reading time
2 min

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 * 2

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns of the matrix, respectively
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview