Minimum Equal Sum of Two Arrays After Replacing Zeros — LeetCode 2918 Python Solution
- Problem
- #2918
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- nums1 = [3,2,0,1,0], nums2 = [6,5,0]
- Output
- 12
- Explanation
- We can replace 0's in the following way:
Python solution
class Solution:
def minSum(self, nums1: List[int], nums2: List[int]) -> int:
s1 = sum(nums1) + nums1.count(0)
s2 = sum(nums2) + nums2.count(0)
if s1 > s2:
return self.minSum(nums2, nums1)
if s1 == s2:
return s1
return -1 if nums1.count(0) == 0 else s2Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m), where n and m are the lengths of the arrays nums1 and nums2, respectively |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros?
- LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros?
- The Python solution on this page runs in O(n + m), where n and m are the lengths of the arrays nums1 and nums2, respectively.
- What is the space complexity of LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros cover?
- LeetCode 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros is tagged Greedy and Array on LeetCode.