Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created May 10, 2025 17:32
Show Gist options
  • Save tatsuyax25/b4e4ceca592a5425375bd6f5108ad4a6 to your computer and use it in GitHub Desktop.
Save tatsuyax25/b4e4ceca592a5425375bd6f5108ad4a6 to your computer and use it in GitHub Desktop.
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 ca
/**
* Function to determine the maximum possible sum by replacing zeros
* in either of the given arrays.
*
* @param {number[]} nums1 - First array of numbers
* @param {number[]} nums2 - Second array of numbers
* @return {number} - Maximum possible sum or -1 if impossible
*/
var minSum = function(nums1, nums2) {
let zeroCount1 = 0; // Count of zeros in nums1
let zeroCount2 = 0; // Count of zeros in nums2
let sum1 = 0; // Sum of all numbers in nums1
let sum2 = 0; // Sum of all numbers in nums2
// Calculate sum of nums1 and count zeros
for (let num of nums1) {
if (num === 0) {
zeroCount1++;
}
sum1 += num;
}
// Calculate sum of nums2 and count zeros
for (let num of nums2) {
if (num === 0) {
zeroCount2++;
}
sum2 += num;
}
// If nums1 would exceed nums2 but cannot be increased, return -1
if (sum1 + zeroCount1 > sum2 + zeroCount2 && zeroCount2 === 0) {
return -1;
}
// If nums2 would exceed nums1 but cannot be increased, return -1
if (sum1 + zeroCount1 < sum2 + zeroCount2 && zeroCount1 === 0) {
return -1;
}
// Return the maximum possible sum after replacing zeros
return Math.max(sum1 + zeroCount1, sum2 + zeroCount2);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment