1975. Maximum Matrix Sum
UnknownView on LeetCode
Time: O(mn)
Space: O(1)
Problem Overview
Maximum Matrix Sum (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Greedy pattern in coding interviews. Sum absolute values; if odd number of negatives subtract 2 * minimum absolute value.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Sum absolute values; if odd number of negatives subtract 2 * minimum absolute value.
1975.cs
C#
// Approach: Sum absolute values; if odd number of negatives subtract 2 * minimum absolute value.
// Time: O(mn) Space: O(1)
public class Solution
{
public long MaxMatrixSum(int[][] matrix)
{
long absSum = 0;
int minAbs = int.MaxValue;
// 0 := even number of negatives
// 1 := odd number of negatives
int oddNeg = 0;
foreach (int[] row in matrix)
{
foreach (int num in row)
{
absSum += Math.Abs(num);
minAbs = Math.Min(minAbs, Math.Abs(num));
if (num < 0)
oddNeg ^= 1;
}
}
return absSum - oddNeg * minAbs * 2;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)