DDSA Solutions

1975. Maximum Matrix Sum

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.

Related patterns: Array, Greedy, Matrix

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