|
| 1 | +// 1975. Maximum Matrix Sum |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/maximum-matrix-sum/ |
| 5 | +// |
| 6 | +// Tags: Array - Greedy - Matrix |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Visit all values in the matrix keeping track of the number of negative values, the smallest |
| 11 | + /// absolute value and the total sum of absolute values. We will be able to find a combination |
| 12 | + /// to flip any two values, that means that, if we have an even number of negative values, we |
| 13 | + /// will be able to flip them all, otherwise, there will be one value that we will not be able |
| 14 | + /// to flip, choose the smallest absolute value. |
| 15 | + /// |
| 16 | + /// Time complexity: O(m*n) - We visit each value in the matrix and do O(1) work for each. |
| 17 | + /// Space complexity: O(1) - The iterator accumulator, one bool, two i64s. |
| 18 | + /// |
| 19 | + /// Runtime 0 ms Beats 100% |
| 20 | + /// Memory 3.19 MB Beats 100% |
| 21 | + pub fn max_matrix_sum(matrix: Vec<Vec<i32>>) -> i64 { |
| 22 | + match matrix.into_iter().flat_map(|row| row.into_iter()).fold( |
| 23 | + (true, i64::MAX, 0i64), |
| 24 | + |acc, x| { |
| 25 | + let a = x.abs() as i64; |
| 26 | + (if x < 0 { !acc.0 } else { acc.0 }, acc.1.min(a), acc.2 + a) |
| 27 | + }, |
| 28 | + ) { |
| 29 | + (true, _, total) => total, |
| 30 | + (false, smallest, total) => total - 2 * smallest, |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +// Tests. |
| 36 | +fn main() { |
| 37 | + let tests = [ |
| 38 | + (vec![vec![1, -1], vec![-1, 1]], 4), |
| 39 | + (vec![vec![1, 2, 3], vec![-1, -2, -3], vec![1, 2, 3]], 16), |
| 40 | + ]; |
| 41 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 42 | + let mut success = 0; |
| 43 | + for (i, t) in tests.iter().enumerate() { |
| 44 | + let res = Solution::max_matrix_sum(t.0.clone()); |
| 45 | + if res == t.1 { |
| 46 | + success += 1; |
| 47 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 48 | + } else { |
| 49 | + println!( |
| 50 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 51 | + i, t.1, res |
| 52 | + ); |
| 53 | + } |
| 54 | + } |
| 55 | + println!(); |
| 56 | + if success == tests.len() { |
| 57 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 58 | + } else if success == 0 { |
| 59 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 60 | + } else { |
| 61 | + println!( |
| 62 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 63 | + tests.len() - success |
| 64 | + ) |
| 65 | + } |
| 66 | +} |
0 commit comments