알고리즘
Minimum Equal Sum of Two Arrays After Replacing Zeros
짬뽕얼큰하게
2025. 5. 12. 08:39
Leetcode Problem:
Summary
- Given two arrays of positive integers, replace all 0's with positive integers to make the sum of both arrays equal, and return the minimum equal sum.
Approach
- This solution first calculates the sum of each array and the number of zeros in each array
- It then checks if it's possible to make the sum of both arrays equal by replacing all zeros with positive integers
- If it's possible, it returns the maximum sum of the two arrays, which is the minimum equal sum
- If it's not possible, it returns -1.
Complexity
- O(n), where n is the total number of elements in both arrays.
Explanation
- The solution iterates over each array to calculate the sum and count of zeros
- It then checks if replacing all zeros with positive integers is possible by checking if the sum of one array is greater than the sum of the other array
- If it's possible, it returns the maximum sum of the two arrays
- If it's not possible, it returns -1.
Solution Code:
class Solution {
public:
long long minSum(vector& nums1, vector& nums2) {
long long sum1 = 0, sum2 = 0;
long long zero1 = 0, zero2 = 0;
for (int i : nums1) {
sum1 += i;
if (i == 0) {
sum1++;
zero1++;
}
}
for (int i : nums2) {
sum2 += i;
if (i == 0) {
sum2++;
zero2++;
}
}
if (!zero1 && sum2 > sum1 || !zero2 && sum1 > sum2) {
return -1;
}
return max(sum1, sum2);
}
};
class Solution {
public:
long long minSum(vector& nums1, vector& nums2) {
long long sum1 = 0, sum2 = 0;
long long zero1 = 0, zero2 = 0;
for (int i : nums1) {
sum1 += i;
if (i == 0) {
sum1++;
zero1++;
}
}
for (int i : nums2) {
sum2 += i;
if (i == 0) {
sum2++;
zero2++;
}
}
if (!zero1 && sum2 > sum1 || !zero2 && sum1 > sum2) {
return -1;
}
return max(sum1, sum2);
}
};