#1975

Maximum Matrix Sum

Medium
ArrayGreedyMatrixGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution leverages the fact that we can maximize the sum by ensuring that we can flip pairs of negative numbers to positive. The key is to count the number of negative numbers and the smallest absolute value to determine if we can achieve the maximum sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total sum of absolute values of all elements in the matrix.
  2. 2Step 2: Count the number of negative elements in the matrix.
  3. 3Step 3: If the count of negative numbers is odd, subtract twice the smallest absolute value from the total sum to account for the unflipped negative number.
solution.py13 lines
1def maxMatrixSum(matrix):
2    total_sum = 0
3    min_abs = float('inf')
4    negative_count = 0
5    for row in matrix:
6        for val in row:
7            total_sum += abs(val)
8            if val < 0:
9                negative_count += 1
10            min_abs = min(min_abs, abs(val))
11    if negative_count % 2 == 1:
12        total_sum -= 2 * min_abs
13    return total_sum

Complexity note: The time complexity remains O(n²) as we still iterate through the matrix. The space complexity is O(1) since we only use a few variables to keep track of counts and sums.

  • 1Flipping adjacent elements can help convert negatives to positives, maximizing the sum.
  • 2The parity of negative numbers (odd/even) determines whether the smallest absolute value affects the total sum.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.