Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created May 10, 2025 22:29
Show Gist options
  • Save Ifihan/7ab0af08b9d2758c2cb11af697c1d983 to your computer and use it in GitHub Desktop.
Save Ifihan/7ab0af08b9d2758c2cb11af697c1d983 to your computer and use it in GitHub Desktop.
Minimum Equal Sum of Two Arrays After Replacing Zeros

Question

Approach

I first calculate the current sum and count of zeroes in both arrays. Since we must replace 0's with positive integers ≥ 1, I consider the minimum possible increment for each zero. I then try to equalize the sums by appropriately choosing values for the zeros. If it’s impossible due to a mismatch in fixed parts, I return -1.

Implementation

class Solution:
    def minSum(self, nums1: List[int], nums2: List[int]) -> int:
        sum1, zero1 = sum(nums1), nums1.count(0)
        sum2, zero2 = sum(nums2), nums2.count(0)

        if zero1 == 0 and zero2 == 0 and sum1 != sum2:
            return -1
   
        min_add1 = zero1 * 1
        min_add2 = zero2 * 1

        if sum1 + min_add1 > sum2 + zero2 * 10**6:
            return -1
        if sum2 + min_add2 > sum1 + zero1 * 10**6:
            return -1

        min_target_1 = sum1 + zero1
        min_target_2 = sum2 + zero2

        if min_target_1 >= sum2 and zero2 > 0:
            return min_target_1
        if min_target_2 >= sum1 and zero1 > 0:
            return min_target_2
        if min_target_1 == min_target_2:
            return min_target_1
        return -1

But then it didn't pass all the test cases (629/636). So I turned to the editorial and it seemed similar so I just used it

image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment