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.
X 关闭
-

快讯:LeetCode 1975. Maximum Matrix Sum
Youaregivenannxnintegermatrix Youcandothefollowingoperationanynumberoftimes:Chooseanytwoadjacentelem
-

方便学子求职 青岛理工大学启用共享面试亭 当前关注
“每次线上面试之前都很犯愁,在宿舍、教室面试可能会被打扰,酒店房间又太贵。现在学校上线了共享面试亭,
-

当前焦点!子果
1、子果,指五蕴之果报,乃过去烦恼所生之果。2、即种子所生之果。文章到此就分享结束,希望对大家有所帮助
-

【全球独家】丰立智能:公司未来规划将充分利用优质存量客户资源,在保持小模数齿轮业务竞争优势的同时积极挖掘小型精密减速器、谐波减速器等产品的业务机会,延伸产业链
同花顺(300033)金融研究中心4月20日讯,有投资者向丰立智能(301368)提问,尊敬的董秘你好,公司的谐波

