Skip to content

Commit 08ddcc8

Browse files
Sync LeetCode submission Runtime - 2 ms (48.80%), Memory - 39.1 MB (61.72%)
1 parent e5fd7b4 commit 08ddcc8

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>You are given an <code>n x n</code> integer <code>matrix</code>. You can do the following operation <strong>any</strong> number of times:</p>
2+
3+
<ul>
4+
<li>Choose any two <strong>adjacent</strong> elements of <code>matrix</code> and <strong>multiply</strong> each of them by <code>-1</code>.</li>
5+
</ul>
6+
7+
<p>Two elements are considered <strong>adjacent</strong> if and only if they share a <strong>border</strong>.</p>
8+
9+
<p>Your goal is to <strong>maximize</strong> the summation of the matrix&#39;s elements. Return <em>the <strong>maximum</strong> sum of the matrix&#39;s elements using the operation mentioned above.</em></p>
10+
11+
<p>&nbsp;</p>
12+
<p><strong class="example">Example 1:</strong></p>
13+
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png" style="width: 401px; height: 81px;" />
14+
<pre>
15+
<strong>Input:</strong> matrix = [[1,-1],[-1,1]]
16+
<strong>Output:</strong> 4
17+
<b>Explanation:</b> We can follow the following steps to reach sum equals 4:
18+
- Multiply the 2 elements in the first row by -1.
19+
- Multiply the 2 elements in the first column by -1.
20+
</pre>
21+
22+
<p><strong class="example">Example 2:</strong></p>
23+
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png" style="width: 321px; height: 121px;" />
24+
<pre>
25+
<strong>Input:</strong> matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
26+
<strong>Output:</strong> 16
27+
<b>Explanation:</b> We can follow the following step to reach sum equals 16:
28+
- Multiply the 2 last elements in the second row by -1.
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>n == matrix.length == matrix[i].length</code></li>
36+
<li><code>2 &lt;= n &lt;= 250</code></li>
37+
<li><code>-10<sup>5</sup> &lt;= matrix[i][j] &lt;= 10<sup>5</sup></code></li>
38+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
long long maxMatrixSum(vector<vector<int>>& matrix) {
4+
int negs = 0;
5+
int mn = 1e9;
6+
long long sum = 0;
7+
for (vector<int>& i : matrix) {
8+
for (int j : i) {
9+
sum += abs(j);
10+
mn = min(mn, abs(j));
11+
if (j < 0) negs++;
12+
}
13+
}
14+
15+
if (negs % 2 != 0) sum -= 2 * mn;
16+
return sum;
17+
}
18+
};

0 commit comments

Comments
 (0)