Input: nums1 =[3,2,0,1,0], nums2 =[6,5,0]Output: 12Explanation: 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 0in 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:
1
2
3
Input: nums1 =[2,0,2,0], nums2 =[1,4]Output: -1Explanation: It is impossible to make the sum of both arrays equal.
The goal is to minimise the equal sum of two arrays after replacing 0s with strictly positive integers (1 in this case). The approach is straightforward:
Initial Sum Calculation:
Compute the sum of elements in both arrays (sum1 and sum2).
Count the number of 0s in both arrays (zero1 and zero2).
Handle Replacement:
Replace 0s with 1 during sum computation.
Adjust the counts zero1 and zero2 while calculating the adjusted sums.
Impossibility Check:
If one array has no 0s and its sum cannot match the other array’s sum (because it cannot be increased or decreased further), return -1.
Result:
Return the maximum possible sum after adjustments since both sums will now be identical.
classSolution:
defminSum(self, nums1: List[int], nums2: List[int]) -> int:
sum1, sum2 =0, 0 zero_count1, zero_count2 =0, 0# Calculate sums and count zeros in nums1for num in nums1:
if num ==0:
sum1 +=1# Replace 0 with 1 zero_count1 +=1else:
sum1 += num
# Calculate sums and count zeros in nums2for num in nums2:
if num ==0:
sum2 +=1# Replace 0 with 1 zero_count2 +=1else:
sum2 += num
# Check if it's impossible to equalise sumsif (zero_count1 ==0and sum2 > sum1) or (zero_count2 ==0and sum1 > sum2):
return-1# Return the maximum adjusted sum (both sums are equalised)return max(sum1, sum2)