[LeetCode] Maximum Matrix Sum

1975. Maximum Matrix Sum

You are given an n x n integer matrix. You can do the following operation any number of times:

  • Choose any two adjacent elements of matrix and multiply each of them by -1.
    Two elements are considered adjacent if and only if they share a border.

Your goal is to maximize the summation of the matrix’s elements. Return the maximum sum of the matrix’s elements using the operation mentioned above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
long long maxMatrixSum(vector<vector<int>>& A) {
bool neg = false;
long long mi = LLONG_MAX, res = 0, n = A.size(), m = A[0].size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
mi = min(mi, 1ll * abs(A[i][j]));
res += abs(A[i][j]);
if(A[i][j] < 0) neg = !neg;
}
}
return res + (neg ? -mi * 2 : 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/13/PS/LeetCode/maximum-matrix-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.