LeetCode 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.

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值