Re: [闲聊] 每日leetcode

楼主: dont   2024-11-24 11:19:10
1975. Maximum Matrix Sum
## 思路
相邻两个值*-1 可以做无限次
所以matrix转换完最多只会有1个负数
检查负数的个数 并记录最小绝对值
如果有偶数个负数, matrix sum会是所有绝对值的和
如果有奇数个负数, matrix sum要再减掉最小绝对值*2
## Code
```python
class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
len_r, len_c = len(matrix), len(matrix[0])
res = 0
curr_min = float('inf')
odd_neg = 0
for r in range(len_r):
for c in range(len_c):
abs_num = abs(matrix[r][c])
res += abs_num
curr_min = min(curr_min, abs_num)
odd_neg ^= (matrix[r][c] < 0)
if odd_neg:
res -= curr_min * 2
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com