|
| 1 | +// 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimum-equal-sum-of-two-arrays-after-replacing-zeros/ |
| 5 | +// |
| 6 | +// Tags: Array - Greedy |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Compute the minimum and maximum we can get from each array, return the minimum value common |
| 11 | + /// to both intervals or -1 if there is no common value. |
| 12 | + /// |
| 13 | + /// Time complexity: O(n+m) |
| 14 | + /// Space complexity: O(1) |
| 15 | + /// |
| 16 | + /// Runtime 16 ms Beats 60% |
| 17 | + /// Memory 3.82 MB Beats % |
| 18 | + pub fn min_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i64 { |
| 19 | + fn min_max(nums: &Vec<i32>) -> (i64, i64) { |
| 20 | + let (s, z) = nums.iter().fold((0, 0), |(s, c), &x| { |
| 21 | + (s + x as i64, c + if x == 0 { 1 } else { 0 }) |
| 22 | + }); |
| 23 | + let min = s + z as i64; |
| 24 | + let max = if z > 0 { i64::MAX } else { min }; |
| 25 | + (min, max) |
| 26 | + } |
| 27 | + let (a, b) = (min_max(&nums1), min_max(&nums2)); |
| 28 | + let (start, end) = (a.0.max(b.0), a.1.min(b.1)); |
| 29 | + if start > end { |
| 30 | + -1 |
| 31 | + } else { |
| 32 | + start |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// Tests. |
| 38 | +fn main() { |
| 39 | + let tests = [ |
| 40 | + (vec![3, 2, 0, 1, 0], vec![6, 5, 0], 12), |
| 41 | + (vec![2, 0, 2, 0], vec![1, 4], -1), |
| 42 | + ]; |
| 43 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 44 | + let mut success = 0; |
| 45 | + for (i, t) in tests.iter().enumerate() { |
| 46 | + let res = Solution::min_sum(t.0.clone(), t.1.clone()); |
| 47 | + if res == t.2 { |
| 48 | + success += 1; |
| 49 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 50 | + } else { |
| 51 | + println!( |
| 52 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 53 | + i, t.2, res |
| 54 | + ); |
| 55 | + } |
| 56 | + } |
| 57 | + println!(); |
| 58 | + if success == tests.len() { |
| 59 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 60 | + } else if success == 0 { |
| 61 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 62 | + } else { |
| 63 | + println!( |
| 64 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 65 | + tests.len() - success |
| 66 | + ) |
| 67 | + } |
| 68 | +} |
0 commit comments