C++ solution | Clean Code | Beats 100%
Intuition\n Describe your first thoughts on how to solve this problem. \nTo get the maximum sum we have to make all (or most) of the negative elements positive.
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get the maximum sum we have to make all (or most) of the negative elements positive. If there are even number of negative elements in the matrix , it can be noted that every element can be made non-negative using the operation irrespective of the position. If there are odd number of negative elements , then only the element with the least absolute value in the matrix will be left negative.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet the sum of absolute values of all the elements and keep track of the minmimum absolute value of the element which is less than equal to $1$ (say $minimum$) and the number of elements that are non-positive (say $count$). Now, if the $count$ is odd then subtract the sum with $minimum$ **twice**.\n\n# Complexity\n- Time complexity:$$O(n^2)$$  (To traverse the matrix.)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    long long maxMatrixSum(vector<vector<int>>& matrix) {\n        int minimum=100000;\n        long long sum=0;\n        int n=matrix.size();\n        int count=0;\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                int x=matrix[i][j];\n                if(x<=0){\n                    count++;\n                    x*=-1;\n                    \n                }\n                minimum=min(minimum,x);\n                sum+=x;\n            }\n        }\n        //check if count is odd \n        if(count&1) sum-=2*minimum;\n        return sum;\n    }\n};\n\n```\n![Screenshot 2024-11-24 141444.png](https://assets.leetcode.com/users/images/8894e175-4d79-4b3d-994c-42010efdcd9d_1732438751.0709665.png)
['C++']