Handling Matrices with Mixed Values in Java 🚀
\n# Approach\n\n- Traverse each element in the matrix using nested loops.\nCalculate Required Values:\n\n- Keep a running sum of absolute values (sum).\nCount t
\n# Approach\n\n- Traverse each element in the matrix using nested loops.\nCalculate Required Values:\n\n- Keep a running sum of absolute values (sum).\nCount the number of negative elements (negativeCount).\n- Track the smallest absolute value (lowest).\nAdjust the Final Sum:\n\n- If the count of negative numbers is odd, subtract 2 \xD7 lowest from the total absolute sum to make it even.\n\n# Complexity\n- Time complexity:\n    - Outer loop runs n times (rows).\n    - Inner loop runs m times (columns).\n    - Overall complexity: **O(n \xD7 m)**, where n is the number of rows and m is the number of columns.\n\n- Space complexity:\n    - The code uses a constant amount of extra space regardless of the matrix size:\n    Variables sum, negativeCount, and lowest take constant space.\n    - No additional data structures are used.\n    - Overall space complexity: O(1) (constant space).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n    public long maxMatrixSum(int[][] matrix) {\n        int n = matrix.length; // Number of rows\n        int m = matrix[0].length; // Number of columns\n\n        long sum = 0; // To store the total absolute sum of all elements\n        int negativeCount = 0; // To count the number of negative values\n        int lowest = Integer.MAX_VALUE; // To track the smallest absolute value in the matrix\n\n        for (int[] rows : matrix) {\n            for (int column = 0; column < m; column++) {\n                // Check if the current element is negative\n                if (rows[column] < 0) {\n                    negativeCount++;\n                }\n                // Update the smallest absolute value found so far\n                lowest = Math.min(lowest, Math.abs(rows[column]));\n\n                // Add the absolute value of the current element to the sum\n                sum += Math.abs(rows[column]);\n            }\n        }\n\n        // Check if the count of negatives is odd or even\n        // If even, return the total sum\n        // If odd, subtract 2 * lowest absolute value to balance the sum\n        return negativeCount % 2 == 0 ? sum : (sum - (2L * lowest));\n    }\n}\n```
['Array', 'Greedy', 'Matrix', 'Java']