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
matrixand 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.
Example 1:

Input: matrix = [[1,-1],[-1,1]] Output: 4 Explanation: We can follow the following steps to reach sum equals 4: - Multiply the 2 elements in the first row by -1. - Multiply the 2 elements in the first column by -1.
Example 2:

Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]] Output: 16 Explanation: We can follow the following step to reach sum equals 16: - Multiply the 2 last elements in the second row by -1.
Constraints:
n == matrix.length == matrix[i].length2 <= n <= 250-10^5 <= matrix[i][j] <= 10^5
题目链接:https://leetcode.com/problems/maximum-matrix-sum/
题目大意:一次操作可任选两相邻格子并让其值都乘-1,可操作无数次,求矩阵和的最大值
题目分析:因为可以操作无数次,若矩阵中有0或负数的个数是偶数,最终必能让所有值非负(0可以用来将任何负数转为正数),故只有矩阵中没有0且有奇数个负数时需要额外考虑,此时也只需看负数的最大值和正数的最小值的绝对值谁更小,减去即可
4ms,时间击败94.71%
class Solution {
public long maxMatrixSum(int[][] matrix) {
int n = matrix.length, negCnt = 0;
int negMa = Integer.MIN_VALUE, posMi = Integer.MAX_VALUE;
long ans = 0;
boolean hasZero = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] < 0) {
negCnt++;
if (negMa < matrix[i][j]) {
negMa = matrix[i][j];
}
} else if (matrix[i][j] > 0) {
if (posMi > matrix[i][j]) {
posMi = matrix[i][j];
}
} else {
hasZero = true;
}
ans += Math.abs(matrix[i][j]);
}
}
if (!hasZero && negCnt % 2 == 1) {
int extra = -negMa < posMi ? -negMa * 2 : posMi * 2;
ans -= extra;
}
return ans;
}
}

该博客讨论了一种优化策略,通过选择矩阵中相邻元素并乘以-1来最大化矩阵元素之和。问题的核心在于确定何时通过操作将负数转换为正数以增加总和。文章分析了当矩阵中没有0且负数个数为奇数时的特殊情况,并提供了高效的解决方案。代码示例展示了如何实现这一算法,以4ms的时间复杂度达到高效率。
365

被折叠的 条评论
为什么被折叠?



