Maximum Matrix Sum LeetCode solution in C++

1
/**
2
* @author : archit
3
* @GitHub : archit-1997
4
* @Email : architsingh456@gmail.com
5
* @file : maximumMatrixSum.cpp
6
* @created : Saturday Aug 21, 2021 20:11:56 IST
7
*/
8

9
#include <bits/stdc++.h>
10
using namespace std;
11

12
class Solution {
13
public:
14
long long maxMatrixSum(vector<vector<int>> &matrix) {
15
int r = matrix.size(), c = matrix[0].size();
16

17
// we need to find the min number in the matrix and also count of negative
18
// numbers in the matrix
19
int small = INT_MAX, count = 0;
20
long long int sum = 0;
21

22
for (int i = 0; i < r; i++) {
23
for (int j = 0; j < c; j++) {
24
int val = matrix[i][j];
25
// finding the smallest absolute value in the matrix
26
small = min(small, abs(val));
27
// counting the negative numbers
28
if (val < 0) count++;
29
// finding the sum of all the values
30
sum += abs(val);
31
}
32
}
33
// if even number of negatives, then just return sum
34
if (count % 2 == 0)
35
return sum;
36
else
37
// subtract the value of the min absolute element
38
return sum - 2 * small;
39
}
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0