Maximum Matrix Sum
Real-world version: Turning Signs in Pairs on the GridThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def max_matrix_sum(grid: list[list[int]]) -> int:public long maxMatrixSum(int[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Score After Flipping MatrixReal-world version: Maximum Relay Cabinet TotalMedium
- Largest Submatrix With RearrangementsReal-world version: Widest Block After Reordering ColumnsMedium
- Minimum Swaps to Arrange a Binary GridReal-world version: Row Shuffles to Clear the DiagonalMedium
- Can Place FlowersReal-world version: Blade Spacing in the RackEasy