#2918
Medium Algorithms Minimum equal sum of two arrays after replacing zeros
Array Greedy
50.2% acceptance
Feb 25, 2026
604
55
You are given two arrays nums1 and nums2 consisting of positive integers.
You have to replace all the 0's in both arrays with strictly positive integers such that the sum of elements of both arrays becomes equal.
Return the minimum equal sum you can obtain, or -1 if it is impossible.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i64 {
let sum1: i64 = nums1.iter().map(|&x| x as i64).sum();
let sum2: i64 = nums2.iter().map(|&x| x as i64).sum();
let zeros1 = nums1.iter().filter(|&&x| x == 0).count() as i64;
let zeros2 = nums2.iter().filter(|&&x| x == 0).count() as i64;
let min1 = sum1 + zeros1; // min possible sum of nums1 (replace each 0 with 1)
let min2 = sum2 + zeros2; // min possible sum of nums2
let target = min1.max(min2);
// If nums1 has no zeros and target > sum1, impossible
if zeros1 == 0 && target > sum1 { return -1; }
// If nums2 has no zeros and target > sum2, impossible
if zeros2 == 0 && target > sum2 { return -1; }
target
}
}