2918. Minimum Equal Sum of Two Arrays After Replacing Zeros
About this solution
Minimum Equal Sum of Two Arrays After Replacing Zeros is a unknown-difficulty LeetCode problem covering the Array, Greedy patterns. The Java solution below uses an idiomatic approach that is clean, readable, and directly submittable on LeetCode. Study the logic carefully — recognising the underlying pattern is the key skill that transfers to similar problems in interviews.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.
import java.util.Arrays;
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);
}
}