1975-maximum-matrix-sum.rs (2119B)
1/// 1975. Maximum Matrix Sum (Medium) 2/// 3/// You are given an n x n integer matrix. You can do the following operation 4/// *any* number of times: 5/// 6/// * Choose any two *adjacent* elements of matrix and *multiply* each of them 7/// by -1. 8/// 9/// Two elements are considered *adjacent* if and only if they share a *border*. 10/// 11/// Your goal is to *maximize* the summation of the matrix's elements. Return 12/// the *maximum* sum of the matrix's elements using the operation mentioned 13/// above. 14/// 15/// *Example 1:* 16/// 17/// *Input:* matrix = [[1,-1],[-1,1]] 18/// *Output:* 4 19/// Explanation: We can follow the following steps to reach sum equals 4: 20/// - Multiply the 2 elements in the first row by -1. 21/// - Multiply the 2 elements in the first column by -1. 22/// 23/// *Example 2:* 24/// 25/// *Input:* matrix = [[1,2,3],[-1,-2,-3],[1,2,3]] 26/// *Output:* 16 27/// Explanation: We can follow the following step to reach sum equals 16: 28/// - Multiply the 2 last elements in the second row by -1. 29/// 30/// *Constraints:* 31/// 32/// * n == matrix.length == matrix[i].length 33/// * 2 <= n <= 250 34/// * -105 <= matrix[i][j] <= 105 35/// 36use leetcode::*; 37 38struct Solution {} 39 40impl Solution { 41 pub fn max_matrix_sum(matrix: Vec<Vec<i32>>) -> i64 { 42 let mut min = i32::MAX; 43 let mut count = 0usize; 44 let mut sum = 0i64; 45 let mut zero = false; 46 for row in matrix { 47 for entry in row { 48 sum += entry.abs() as i64; 49 min = min.min(entry.abs()); 50 zero |= entry == 0; 51 count += (entry < 0) as usize; 52 } 53 } 54 if !zero && count % 2 == 1 { 55 sum -= 2 * min as i64; 56 } 57 sum 58 } 59} 60 61pub fn main() { 62 println!("{:?}", Solution::max_matrix_sum(arg_into(1))); 63} 64 65#[cfg(test)] 66mod tests { 67 use crate::Solution; 68 use leetcode::vvi; 69 70 #[test] 71 fn test() { 72 assert_eq!(Solution::max_matrix_sum(vvi("[[1,-1],[-1,1]]")), 4); 73 assert_eq!( 74 Solution::max_matrix_sum(vvi("[[1,2,3],[-1,-2,-3],[1,2,3]]")), 75 16 76 ); 77 } 78}