Medium
You are given two arrays nums1
and nums2
consisting of positive integers.
You have to replace all the 0
’s in both arrays with strictly positive integers such that the sum of elements of both arrays becomes equal.
Return the minimum equal sum you can obtain, 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:
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.
Constraints:
1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[i] <= 106
class Solution {
fun minSum(nums1: IntArray, nums2: IntArray): Long {
val sum1 = nums1.fold(0L) { sum, element -> sum + element }
val zeroCount1 = nums1.count { it == 0 }
val sum2 = nums2.fold(0L) { sum, element -> sum + element }
val zeroCount2 = nums2.count { it == 0 }
if (
(zeroCount1 == 0 && sum1 < sum2 + zeroCount2) ||
(zeroCount2 == 0 && sum2 < sum1 + zeroCount1)
) {
return -1
}
return Math.max(sum1 + zeroCount1, sum2 + zeroCount2)
}
}