题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个方阵,现在可以对其中做任意次的操作,即将相邻的两个元素乘以 -1,求操作后方阵的最大和是多少。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
total, negative_count = 0, 0
min_negative = inf
for row in matrix:
for x in row:
if x < 0:
x = -x
negative_count += 1
min_negative = min(min_negative, x)
total += x
if negative_count % 2:
total -= min_negative * 2 # 乘二是因为这个数之间加上去过,要先去除之前的值再减
return total