✅✅Beats 100% |🔥🔥 Wild - Fire Solution🔥🔥 | Easy and Simple ✅
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves maximizing the sum of the matrix elements by flipping signs of adj
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves maximizing the sum of the matrix elements by flipping signs of adjacent elements. The key observation is that we can freely flip signs of any element as long as the total number of negative elements remains consistent modulo 2 (even or odd). The optimal approach is to:\n\n1. Convert all elements to their absolute values.\n2. Leave one smallest absolute value negative if the number of negatives in the matrix is odd. This ensures the largest possible sum while respecting the constraints of the operation.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Iterate through the matrix:**\n    - Compute the absolute sum of all elements to determine the theoretical maximum.\n    - Count the number of negative elements.\n    - Track the smallest absolute value in the matrix.\n\n2. **Adjust for Odd Negatives:**\n    - If the number of negative elements is odd, we cannot make all values positive. Subtract 2\xD7smallest_absolute_value from the absolute sum to leave this one value negative.\n\n3. **Return the Result:**\n    - The final adjusted sum represents the maximum achievable sum after applying the operations.\n# Complexity\n- Time complexity:O(n**2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n    def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n        # Initialize variables\n        total_sum = 0\n        num_negatives = 0\n        smallest_abs_value = float(\'inf\')\n        \n        # Iterate through the matrix\n        for row in matrix:\n            for value in row:\n                # Accumulate the total absolute sum\n                total_sum += abs(value)\n                # Count negative elements\n                if value < 0:\n                    num_negatives += 1\n                # Track the smallest absolute value\n                smallest_abs_value = min(smallest_abs_value, abs(value))\n        \n        # Adjust the sum if the number of negatives is odd\n        if num_negatives % 2 == 1:\n            total_sum -= 2 * smallest_abs_value\n        \n        return total_sum\n\n```\n```java []\nclass Solution {\n    public long maxMatrixSum(int[][] matrix) {\n        long totalSum = 0; // Total absolute sum\n        int numNegatives = 0; // Count of negative numbers\n        int smallestAbsValue = Integer.MAX_VALUE; // Smallest absolute value\n        \n        // Traverse the matrix\n        for (int i = 0; i < matrix.length; i++) {\n            for (int j = 0; j < matrix[i].length; j++) {\n                int value = matrix[i][j];\n                totalSum += Math.abs(value); // Add absolute value to total sum\n                \n                if (value < 0) {\n                    numNegatives++; // Count negatives\n                }\n                \n                // Track smallest absolute value\n                smallestAbsValue = Math.min(smallestAbsValue, Math.abs(value));\n            }\n        }\n        \n        // If the number of negatives is odd, adjust the sum\n        if (numNegatives % 2 == 1) {\n            totalSum -= 2L * smallestAbsValue; // Subtract twice the smallest absolute value\n        }\n        \n        return totalSum;\n    }\n}\n\n```\n```python []\nclass Solution:\n    def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n        # Initialize variables\n        total_sum = 0\n        num_negatives = 0\n        smallest_abs_value = float(\'inf\')\n        \n        # Iterate through the matrix\n        for row in matrix:\n            for value in row:\n                # Accumulate the total absolute sum\n                total_sum += abs(value)\n                # Count negative elements\n                if value < 0:\n                    num_negatives += 1\n                # Track the smallest absolute value\n                smallest_abs_value = min(smallest_abs_value, abs(value))\n        \n        # Adjust the sum if the number of negatives is odd\n        if num_negatives % 2 == 1:\n            total_sum -= 2 * smallest_abs_value\n        \n        return total_sum\n```\n```ruby []\nclass Solution\n  def max_matrix_sum(matrix)\n    total_sum = 0       # Total absolute sum\n    num_negatives = 0   # Count of negative numbers\n    smallest_abs_value = Float::INFINITY # Smallest absolute value\n    \n    # Traverse the matrix\n    matrix.each do |row|\n      row.each do |value|\n        total_sum += value.abs # Add absolute value to total sum\n        \n        # Count negative numbers\n        num_negatives += 1 if value < 0\n        \n        # Track the smallest absolute value\n        smallest_abs_value = [smallest_abs_value, value.abs].min\n      end\n    end\n    \n    # If the number of negatives is odd, adjust the sum\n    if num_negatives.odd?\n      total_sum -= 2 * smallest_abs_value # Subtract twice the smallest absolute value\n    end\n    \n    total_sum\n  end\nend\n\n```\n```javascript []\nclass Solution {\n  maxMatrixSum(matrix) {\n    let totalSum = 0; // Total absolute sum\n    let numNegatives = 0; // Count of negative numbers\n    let smallestAbsValue = Infinity; // Smallest absolute value\n\n    // Traverse the matrix\n    for (let row of matrix) {\n      for (let value of row) {\n        totalSum += Math.abs(value); // Add absolute value to total sum\n\n        // Count negative numbers\n        if (value < 0) {\n          numNegatives++;\n        }\n\n        // Track the smallest absolute value\n        smallestAbsValue = Math.min(smallestAbsValue, Math.abs(value));\n      }\n    }\n\n    // If the number of negatives is odd, adjust the sum\n    if (numNegatives % 2 === 1) {\n      totalSum -= 2 * smallestAbsValue; // Subtract twice the smallest absolute value\n    }\n\n    return totalSum;\n  }\n}\n\n```\n```C++ []\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <limits.h>\nusing namespace std;\n\nclass Solution {\npublic:\n    long long maxMatrixSum(vector<vector<int>>& matrix) {\n        long long totalSum = 0; // Total absolute sum\n        int numNegatives = 0;  // Count of negative numbers\n        int smallestAbsValue = INT_MAX; // Smallest absolute value\n\n        // Traverse the matrix\n        for (const auto& row : matrix) {\n            for (int value : row) {\n                totalSum += abs(value); // Add absolute value to total sum\n\n                // Count negative numbers\n                if (value < 0) {\n                    numNegatives++;\n                }\n\n                // Track the smallest absolute value\n                smallestAbsValue = min(smallestAbsValue, abs(value));\n            }\n        }\n\n        // If the number of negatives is odd, adjust the sum\n        if (numNegatives % 2 == 1) {\n            totalSum -= 2 * smallestAbsValue; // Subtract twice the smallest absolute value\n        }\n\n        return totalSum;\n    }\n};\n\n```\n```C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n    public long MaxMatrixSum(int[][] matrix) {\n        long totalSum = 0; // Total absolute sum\n        int numNegatives = 0; // Count of negative numbers\n        int smallestAbsValue = int.MaxValue; // Smallest absolute value\n\n        // Traverse the matrix\n        foreach (var row in matrix) {\n            foreach (var value in row) {\n                totalSum += Math.Abs(value); // Add absolute value to total sum\n\n                // Count negative numbers\n                if (value < 0) {\n                    numNegatives++;\n                }\n\n                // Track the smallest absolute value\n                smallestAbsValue = Math.Min(smallestAbsValue, Math.Abs(value));\n            }\n        }\n\n        // If the number of negatives is odd, adjust the sum\n        if (numNegatives % 2 == 1) {\n            totalSum -= 2 * smallestAbsValue; // Subtract twice the smallest absolute value\n        }\n\n        return totalSum;\n    }\n}\n\n```\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\n// Function to calculate the maximum matrix sum\nlong long maxMatrixSum(int** matrix, int n) {\n    long long totalSum = 0; // Total absolute sum\n    int numNegatives = 0;   // Count of negative numbers\n    int smallestAbsValue = INT_MAX; // Smallest absolute value\n\n    // Traverse the matrix\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            int value = matrix[i][j];\n            totalSum += abs(value); // Add absolute value to total sum\n\n            // Count negative numbers\n            if (value < 0) {\n                numNegatives++;\n            }\n\n            // Track the smallest absolute value\n            if (abs(value) < smallestAbsValue) {\n                smallestAbsValue = abs(value);\n            }\n        }\n    }\n\n    // If the number of negatives is odd, adjust the sum\n    if (numNegatives % 2 == 1) {\n        totalSum -= 2 * smallestAbsValue; // Subtract twice the smallest absolute value\n    }\n\n    return totalSum;\n}\n\n// Helper function to create a 2D array\nint** createMatrix(int n) {\n    int** matrix = (int**)malloc(n * sizeof(int*));\n    for (int i = 0; i < n; i++) {\n        matrix[i] = (int*)malloc(n * sizeof(int));\n    }\n    return matrix;\n}\n\n// Helper function to free a 2D array\nvoid freeMatrix(int** matrix, int n) {\n    for (int i = 0; i < n; i++) {\n        free(matrix[i]);\n    }\n    free(matrix);\n}\n\n// Example usage\nint main() {\n    int n = 2;\n    int** matrix = createMatrix(n);\n\n    matrix[0][0] = 1; matrix[0][1] = -1;\n    matrix[1][0] = -1; matrix[1][1] = 1;\n\n    printf("Maximum Matrix Sum: %lld\\n", maxMatrixSum(matrix, n));\n\n    freeMatrix(matrix, n);\n\n    n = 3;\n    matrix = createMatrix(n);\n\n    matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;\n    matrix[1][0] = -1; matrix[1][1] = -2; matrix[1][2] = -3;\n    matrix[2][0] = 1; matrix[2][1] = 2; matrix[2][2] = 3;\n\n    printf("Maximum Matrix Sum: %lld\\n", maxMatrixSum(matrix, n));\n\n    freeMatrix(matrix, n);\n\n    return 0;\n}\n\n```\n```Go []\npackage main\n\nimport (\n\t"math"\n)\n\nfunc maxMatrixSum(matrix [][]int) int64 {\n\tvar totalSum int64 = 0      // Total absolute sum\n\tnumNegatives := 0           // Count of negative numbers\n\tsmallestAbsValue := math.MaxInt64 // Smallest absolute value\n\n\t// Traverse the matrix\n\tfor _, row := range matrix {\n\t\tfor _, value := range row {\n\t\t\ttotalSum += int64(abs(value)) // Add absolute value to total sum\n\n\t\t\t// Count negative numbers\n\t\t\tif value < 0 {\n\t\t\t\tnumNegatives++\n\t\t\t}\n\n\t\t\t// Track the smallest absolute value\n\t\t\tif abs(value) < smallestAbsValue {\n\t\t\t\tsmallestAbsValue = abs(value)\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the number of negatives is odd, adjust the sum\n\tif numNegatives%2 == 1 {\n\t\ttotalSum -= 2 * int64(smallestAbsValue) // Subtract twice the smallest absolute value\n\t}\n\n\treturn totalSum\n}\n\n// Helper function to calculate the absolute value\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n\n```\n```PHP []\n<?php\n\nfunction maxMatrixSum($matrix) {\n    $totalSum = 0;  // Total absolute sum\n    $numNegatives = 0;  // Count of negative numbers\n    $smallestAbsValue = PHP_INT_MAX; // Smallest absolute value\n\n    // Traverse the matrix\n    foreach ($matrix as $row) {\n        foreach ($row as $value) {\n            $totalSum += abs($value); // Add absolute value to total sum\n\n            // Count negative numbers\n            if ($value < 0) {\n                $numNegatives++;\n            }\n\n            // Track the smallest absolute value\n            if (abs($value) < $smallestAbsValue) {\n                $smallestAbsValue = abs($value);\n            }\n        }\n    }\n\n    // If the number of negatives is odd, adjust the sum\n    if ($numNegatives % 2 == 1) {\n        $totalSum -= 2 * $smallestAbsValue; // Subtract twice the smallest absolute value\n    }\n\n    return $totalSum;\n}\n\n?>\n\n```\n![upvote.png](https://assets.leetcode.com/users/images/06dab959-687c-4c22-8ca0-75a8849ab49d_1732414420.597937.png)\n\n
['Array', 'C', 'PHP', 'C++', 'Java', 'Go', 'Python3', 'Ruby', 'JavaScript', 'C#']