Show problems as
Classic problem #2918MediumArrayGreedy

Minimum Equal Sum of Two Arrays After Replacing Zeros

Real-world version: Filling the Blanks So Two Tallies Match
Tracked in this browser only
Read Minimum Equal Sum of Two Arrays After Replacing Zeros on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Two sheets of figures read left and right. A 0 on either sheet is a blank that has to be filled in with a whole number of 1 or more; every other figure stays as it is.

Fill in all the blanks so that the two sheets come to the same total. Return the smallest total both can be brought to, or -1 when no filling makes them meet.

Examples

Example 1

Input
left = [3, 2, 0, 1, 0], right = [6, 5, 0]
Output
12

The left sheet has six written and two blanks, so its floor is eight. The right sheet has eleven written and one blank, so its floor is twelve. Twelve is the larger, and the left sheet reaches it by writing 1 in one blank and 5 in the other.

Example 2

Input
left = [2, 0, 2, 0], right = [1, 4]
Output
-1

The left sheet has four written and two blanks, so it can never total less than six. The right sheet has no blanks at all and is stuck at five, so the two can never meet.

Example 3

Input
left = [6], right = [6]
Output
6

Neither sheet has a blank and both already total six, so six is the only total either can show.

Constraints

  • 1 <= left.length <= 10^5
  • 1 <= right.length <= 10^5
  • 0 <= left[i] <= 10^6
  • 0 <= right[i] <= 10^6

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def min_sum(left: list[int], right: list[int]) -> int:
Java
public long minSum(int[] left, int[] right)