您的位置:首页 >互联网 >

今热点:LeetCode 1975. Maximum Matrix Sum

You are given an n x ninteger 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.

因为2个相邻的数字可以同时乘以-1,所以我们就可以将任意的数字组合乘以-1,这时候就要计算数组中一共有多少个负数,如果是偶数个,那么一定可以全部取正,如果是奇数个,我们就让最小的那个数字变成负数即可;

剩下就是几个变量,求和项(所有数取绝对值),负数的数量,最小的数(绝对值之后);

然后分2种情况依次返回即可;

题目不算太难的。

Constraints:

n == matrix.length == matrix[i].length

2 <= n <= 250

-105 <= matrix[i][j] <= 105

Runtime: 6 ms, faster than 93.02% of Java online submissions for Maximum Matrix Sum.

Memory Usage: 53 MB, less than 36.05% of Java online submissions for Maximum Matrix Sum.

关键词:

热点