Skip to content

Instantly share code, notes, and snippets.

@D-Lite
Created January 5, 2026 08:57
Show Gist options
  • Select an option

  • Save D-Lite/ff1e489446ff27067869bbde1a0a5fb4 to your computer and use it in GitHub Desktop.

Select an option

Save D-Lite/ff1e489446ff27067869bbde1a0a5fb4 to your computer and use it in GitHub Desktop.
Jan 5
My first approach was to go round all at once, in a greedy approach way. But it was figuring the movement of the negative signs around the matrix.
Watching neetcode helped.
Now, we just sum all numbers as absolute. We also keep track of negative numbers on the go
Then at the end, if we check the modulo of the number of negative numbers, and it remains 1, we can then negate the minimum absolute value and double subtract it from the total sum we had earlier.
```
use std::cmp;
impl Solution {
pub fn max_matrix_sum(matrix: Vec<Vec<i32>>) -> i64 {
let mut total_sum: i64 = 0;
let mut min_abs_val = i32::MAX;
let mut neg_count = 0;
for row in matrix {
for col in row {
let abs_val = col.abs();
total_sum += abs_val as i64;
min_abs_val = cmp::min(min_abs_val, abs_val);
if col < 0 {
neg_count += 1;
}
}
}
if neg_count % 2 != 0 {
total_sum -= 2 * (min_abs_val as i64);
}
return total_sum as i64;
}
}
```
Time Complexity: O(col * row)
Space: O(1)
Link to neetcode: https://www.youtube.com/watch?v=XonYlqE049I
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment