Approach

This is a math like problem, I think that if a list is given we can always swap the first one to positive and propagate the operation.

In the end, there might be no negative number or just a negative number in the end. This depends on the total number of negative numbers in the original case, since the operatoin would not change the odd/even for the total negative count, if original matrix is having odd count, the last element would be negative.

I’m thinking that we perhaps can make any element in the matrix as the last one for the matrix, and then I find out that we can generalize more for the list propagation. Actually we can propagate from both end, and make any element as the last one for a list, and the way to flatten a matrix is to walk in a spiral matter, in this case we can make any elemenet the last one.

Therefore, we just need to sum all the abs value up, maintain the negative count, and find the minimum abs value. In the end, we minus twice of the mini when having odd neg. count.

Code

class Solution {
public:
    long long maxMatrixSum(vector<vector<int>>& matrix) {
        long long sum = 0;
        int negCnt = 0;
        int minNum = INT_MAX;
        int m = matrix.size();
        int n = matrix[0].size();
        for(int i = 0 ; i < m ; ++i) {
            for(int j = 0 ; j < n ; ++j) {
                int& curNum = matrix[i][j];
                if(curNum < 0) {
                    curNum = -curNum;
                    ++negCnt;
                }
                minNum = min(curNum, minNum);
                sum += curNum;
            }
        }
        return negCnt % 2 == 0 ? sum : sum - 2*minNum;
    }
};