2918. Minimum Equal Sum of Two Arrays After Replacing Zeros #1666
-
Topics: You are given two arrays You have to replace all the Return the minimum equal sum you can obtain, or Example 1:
**Example 2:**nums1 = [2,0,2,0], nums2 = [1,4]
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to replace all zeros in two given arrays with strictly positive integers such that the sums of both arrays become equal, and we need to find the minimum possible equal sum. If it's impossible, we return -1. Approach
Let's implement this solution in PHP: 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros <?php
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @return Integer
*/
function minSum($nums1, $nums2) {
$sum1 = 0;
$zeros1 = 0;
foreach ($nums1 as $num) {
if ($num == 0) {
$zeros1++;
} else {
$sum1 += $num;
}
}
$sum2 = 0;
$zeros2 = 0;
foreach ($nums2 as $num) {
if ($num == 0) {
$zeros2++;
} else {
$sum2 += $num;
}
}
$min1 = ($zeros1 > 0) ? ($sum1 + $zeros1) : $sum1;
$min2 = ($zeros2 > 0) ? ($sum2 + $zeros2) : $sum2;
if ($zeros1 > 0 && $zeros2 > 0) {
return max($min1, $min2);
} elseif ($zeros1 == 0 && $zeros2 == 0) {
return ($sum1 == $sum2) ? $sum1 : -1;
} else {
if ($zeros1 == 0) {
$s_fixed = $sum1;
$other_min = $min2;
} else {
$s_fixed = $sum2;
$other_min = $min1;
}
return ($s_fixed >= $other_min) ? $s_fixed : -1;
}
}
// Test cases
print_r(minSum([3, 2, 0, 1, 0], [6, 5, 0])); // Output: 12
print_r(minSum([2, 0, 2, 0], [1, 4])); // Output: -1
?> Explanation:
This approach efficiently determines the minimum possible equal sum by leveraging the constraints and properties of the arrays, ensuring optimal performance. |
Beta Was this translation helpful? Give feedback.
We need to replace all zeros in two given arrays with strictly positive integers such that the sums of both arrays become equal, and we need to find the minimum possible equal sum. If it's impossible, we return -1.
Approach