Minimum Equal Sum of Two Arrays After Replacing Zeros

Language Options

C++ Solution |
Python Solution

Code Solution


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);
  }
}

Problem Description

Ah, the classic dilemma of two arrays trying to find common ground—like two friends arguing over who gets the last slice of pizza. The problem at hand is to determine the minimum equal sum of two arrays after replacing zeros. Imagine you have two arrays, nums1 and nums2, and you can replace zeros in these arrays with any positive integer. Your goal? To make the sums of both arrays equal, or at least as close as possible, while keeping the replacements to a minimum.

In simpler terms, if you have two friends who are both broke (hence the zeros), you need to figure out how to make their total money equal without giving them too much cash. If one friend has $5 and the other has $0, you can't just give the broke friend $10 and call it a day. You need to strategize!

Approach Explanation

The code provided does the following:

  1. It calculates the sum of both arrays and counts the number of zeros in each.
  2. It checks if either array can be made equal to the other by replacing zeros. If not, it returns -1.
  3. Finally, it returns the maximum possible sum after considering the zeros.

Time and Space Complexity

Time Complexity: O(n), where n is the length of the longer array. This is because we are iterating through each array to calculate the sums and count the zeros.
Space Complexity: O(1), as we are using a constant amount of space for storing sums and counts.

Real-World Example

Imagine you and your friend are at a restaurant, and you both ordered different meals. You ordered a burger (array 1) and your friend ordered a salad (array 2). However, you both ended up with a side of fries (zeros). Now, to make your meals equal, you can either add more fries or swap some fries for a dessert. The goal is to make sure both meals are equally satisfying without overloading on fries.

Similar Problems

If you enjoyed this problem, you might also like:

  • Two Sum Solution in Java
  • Three Sum Solution in Java
  • Four Sum Solution in Java