Skip to content

Commit a182b66

Browse files
Lam Thanh PhatLam Thanh Phat
authored andcommitted
26/5/25
1 parent 79ab394 commit a182b66

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# You are given two arrays nums1 and nums2 consisting of positive integers.
2+
3+
# 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.
4+
5+
# Return the minimum equal sum you can obtain, or -1 if it is impossible.
6+
7+
8+
9+
# Example 1:
10+
11+
# Input: nums1 = [3,2,0,1,0], nums2 = [6,5,0]
12+
# Output: 12
13+
# Explanation: We can replace 0's in the following way:
14+
# - Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
15+
# - Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
16+
# Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.
17+
# Example 2:
18+
19+
# Input: nums1 = [2,0,2,0], nums2 = [1,4]
20+
# Output: -1
21+
# Explanation: It is impossible to make the sum of both arrays equal.
22+
23+
24+
class Solution(object):
25+
def minSum(self, nums1, nums2):
26+
"""
27+
:type nums1: List[int]
28+
:type nums2: List[int]
29+
:rtype: int
30+
"""
31+
sum_nums1, sum_nums2 = 0, 0
32+
n_zeros_nums1, n_zeros_nums2 = 0, 0
33+
for num in nums1:
34+
sum_nums1 += num
35+
if num == 0:
36+
sum_nums1 += 1
37+
n_zeros_nums1 += 1
38+
39+
for num in nums2:
40+
sum_nums2 += num
41+
if num == 0:
42+
sum_nums2 += 1
43+
n_zeros_nums2 += 1
44+
45+
46+
if (n_zeros_nums1 == 0 and sum_nums1 < sum_nums2) \
47+
or (n_zeros_nums2 == 0 and sum_nums1 > sum_nums2):
48+
return -1
49+
50+
return max(sum_nums1, sum_nums2)

0 commit comments

Comments
 (0)