#2870

Minimum Number of Operations to Make Array Empty

specialist · 680 · lc medium +30 · verified · 62.1% accepted · 1,442 likes · top 63%

Description

A 0-indexed array nums of positive integers is given. You may apply either of these operations any number of times:

- Remove two elements with equal values.

- Remove three elements with equal values.

Return the minimum number of operations to empty the array, or -1 if it is impossible.

Example 1:

Input: nums = [2,3,3,2,2,4,2,3,4]
Output: 4
Explanation: We can apply the following operations to make the array empty:
- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4].
- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4].
- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4].
- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = [].
It can be shown that we cannot make the array empty in less than 4 operations.

Example 2:

Input: nums = [2,1,2,2,3,3]
Output: -1
Explanation: It is impossible to empty the array.

Code

1
2
3