2025-05-10 Daily Challenge

Today I have done leetcode's May LeetCoding Challenge with cpp.

May LeetCoding Challenge 10

Description

Minimum Equal Sum of Two Arrays After Replacing Zeros

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:
- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].
- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].
Both arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.

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

Solution

class Solution {
public:
  long long minSum(vector<int>& nums1, vector<int>& nums2) {
    long long minSum1 = 0;
    long long minSum2 = 0;
    bool hasZero1 = false;
    bool hasZero2 = false;
    for(auto n : nums1) {
      minSum1 += max(1, n);
      if(!n) hasZero1 = true;
    }
    for(auto n : nums2) {
      minSum2 += max(1, n);
      if(!n) hasZero2 = true;
    }
    if(hasZero1 && hasZero2) {
      return max(minSum1, minSum2);
    } else if(hasZero1) {
      return minSum2 >= minSum1 ? minSum2 : -1;
    } else if(hasZero2) {
      return minSum1 >= minSum2 ? minSum1 : -1;
    }
    return minSum1 == minSum2 ? minSum1 : -1;
  }
};

// Accepted
// 636/636 cases passed (135 ms)
// Your runtime beats 40.68 % of cpp submissions
// Your memory usage beats 6.1 % of cpp submissions (135.7 MB)