DDSA Solutions

2918. Minimum Equal Sum of Two Arrays After Replacing Zeros

Problem Overview

Minimum Equal Sum of Two Arrays After Replacing Zeros is a unknown-difficulty LeetCode problem. This is a common Array / Greedy pattern in coding interviews. Study the solution below and note the time and space complexity before attempting variations on your own.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Read the solution code below and trace through it on paper before submitting. For structured interview prep, follow our 30-day study guide.

2918.java
Java
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);
    }
}
Was this solution helpful?

Related Problems