easy +10 pts

Reduce array to zero

Use two pointers to find the minimum number of operations to reduce an array to all zeros.

You are given a list of non-negative integers. In one operation you may choose any two indices i and j such that i != j and both nums[i] and nums[j] are strictly positive, then subtract 1 from both. Return the minimum number of operations needed to make every element zero. If it is impossible, return -1. Write a function `min_operations_to_zero(nums: list[int]) -> int` that implements this. For example: - `[1, 1]` → 1 (choose 0 and 1) - `[5]` → -1 (can never pick two indices) - `[1, 0, 1]` → 1 (choose 0 and 2) - `[2, 2, 2]` → 3 - `[0, 0, 0]` → 0

Constraints

- 0 ≤ len(nums) ≤ 100,000 - 0 ≤ nums[i] ≤ 10^9 - Time complexity target: O(n) or O(n log n).

Example

```python
>>> min_operations_to_zero([1, 1])
1
>>> min_operations_to_zero([5])
-1
>>> min_operations_to_zero([1, 0, 1])
1
>>> min_operations_to_zero([2, 2, 2])
3
>>> min_operations_to_zero([0, 0, 0])
0
```
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about what happens if the array has length 1.
The total sum parity matters: each operation subtracts 2 from the total sum.
Consider the maximum element: when the others are exhausted, can you still reduce the maximum?
For two pointers, think of pairing the largest elements repeatedly and count operations.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.