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.
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].length
2 <= 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;
}
}