Created
January 5, 2026 08:57
-
-
Save D-Lite/ff1e489446ff27067869bbde1a0a5fb4 to your computer and use it in GitHub Desktop.
Jan 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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