Minimum Number of Operations to Make Array Empty

You are given a 0-indexed array nums consisting of positive integers.

There are two types of operations that you can apply on the array any number of times:

  • Choose two elements with equal values and delete them from the array.
  • Choose three elements with equal values and delete them from the array.

Return the minimum number of operations required to make the array empty, or -1 if it is not possible.

Note: This question is the same as 2244: Minimum Rounds to Complete All Tasks.

Example 1
Inputnums = [2,3,3,2,2,4,2,3,4]
Output4
The array can be emptied in 4 operations by deleting equal pairs and triples, and it cannot be done in fewer operations.
Example 2
Inputnums = [2,1,2,2,3,3]
Output-1
It is impossible to empty the array because at least one value cannot be removed using groups of two or three equal elements.

Constraints

  • 2 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate