Skip to content

2918. Minimum Equal Sum of Two Arrays After Replacing Zeros 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  long long minSum(vector<int>& nums1, vector<int>& nums2) {
    const long sum1 = accumulate(nums1.begin(), nums1.end(), 0L);
    const long sum2 = accumulate(nums2.begin(), nums2.end(), 0L);
    const int zero1 = ranges::count(nums1, 0);
    const int zero2 = ranges::count(nums2, 0);
    if (zero1 == 0 && sum1 < sum2 + zero2)
      return -1;
    if (zero2 == 0 && sum2 < sum1 + zero1)
      return -1;
    return max(sum1 + zero1, sum2 + zero2);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public long minSum(int[] nums1, int[] nums2) {
    final long sum1 = Arrays.stream(nums1).asLongStream().sum();
    final long sum2 = Arrays.stream(nums2).asLongStream().sum();
    final long zero1 = Arrays.stream(nums1).filter(num -> num == 0).count();
    final long zero2 = Arrays.stream(nums2).filter(num -> num == 0).count();
    if (zero1 == 0 && sum1 < sum2 + zero2)
      return -1;
    if (zero2 == 0 && sum2 < sum1 + zero1)
      return -1;
    return Math.max(sum1 + zero1, sum2 + zero2);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minSum(self, nums1: list[int], nums2: list[int]) -> int:
    sum1 = sum(nums1)
    sum2 = sum(nums2)
    zero1 = nums1.count(0)
    zero2 = nums2.count(0)
    if zero1 == 0 and sum1 < sum2 + zero2:
      return -1
    if zero2 == 0 and sum2 < sum1 + zero1:
      return -1
    return max(sum1 + zero1, sum2 + zero2)