Maximum Matrix Sum

You are given an n x n integer matrix. You can do the following operation any number of times: choose two adjacent elements (sharing a border) and multiply each of them by -1. Return the maximum possible sum of the matrix elements.

30:00

Maximum Matrix Sum
medium
Free written solution
Topics
Companies

You are given an n x n integer matrix. You can do the following operation any number of times: choose two adjacent elements (sharing a border) and multiply each of them by -1. Return the maximum possible sum of the matrix elements.

Example 1:
Input: {"matrix":[[1,-1],[-1,1]]}
Output: 4
Constraints:
  • n=matrix.length=matrix[i].lengthn = \text{matrix.length} = \text{matrix}[i]\text{.length}

  • 2≤n≤2502 \leq n \leq 250

  • −105≤matrix[i][j]≤105-10^5 \leq \text{matrix}[i][j] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"matrix":[[1,-1],[-1,1]]}

An operation flips the signs of two adjacent cells. Chaining operations moves a minus sign anywhere, so only how many negatives there are matters.

total

0

neg

0 (even)

smallest |x|

–

1
-1
-1
1

negative

flipped in a pair

smallest |x|

Variables
VariableValue
n2
DepthFunction Call
Stack empty
0/7