#2918

Minimum Equal Sum of Two Arrays After Replacing Zeros

specialist · 875 · lc medium +31 · verified · 50.2% accepted · 604 likes · top 38%

Description

Two arrays nums1 and nums2 of positive integers are given. Substitute each 0 in either array with some strictly positive integer such that both arrays end up with the same total sum.

Return the minimum common sum achievable, or -1 if it is impossible.

Example 1:

Input: nums1 = [3,2,0,1,0], nums2 = [6,5,0]
Output: 12
Explanation: We can replace 0's in the following way:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.

Example 2:

Input: nums1 = [2,0,2,0], nums2 = [1,4]
Output: -1
Explanation: It is impossible to make the sum of both arrays equal.

Code

1
2
3