All problems
1175MediumArrayGreedyMatrix

Turning Signs in Pairs on the Grid

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1975Maximum Matrix Sum

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A square grid grid holds whole numbers, some of them below zero. One move picks two cells sharing a side and turns the sign of both of them.

Return the largest total the grid's cells can add up to after any number of moves.

Examples

Example 1

Input
grid = [[-1, 1], [1, 1]]
Output
2

One cell is below zero, and every move turns two signs, so the count of negatives can only change by two. One cell must stay negative, and the cheapest to leave is the smallest in size.

Example 2

Input
grid = [[0, -1], [1, 1]]
Output
3

One cell is below zero again, but a cell holding nothing costs nothing to leave negative, so every other cell can be made positive.

Example 3

Input
grid = [[2, -3], [5, -7]]
Output
17

Two cells are below zero, so both can be turned positive and the whole grid adds up in size.

Constraints

  • 2 <= grid.length <= 250
  • grid[i].length == grid.length
  • -10^5 <= grid[i][j] <= 10^5

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def max_matrix_sum(grid: list[list[int]]) -> int:
Java
public long maxMatrixSum(int[][] grid)
September 7
Apply