Intuition

To minimize the number of operations, we need to delete 3 elements as much as possible. Which means we have to divide each element's count by 3, resulting in three possible scenarios:

  1. Remainder = 0: The total number of operations is the "quotient" of dividing the count by 3.
  2. Remainder = 1: The total number of operations is the "quotient" of dividing the count by 3 plus 1 (the last operation should delete 2 elements, and an additional operation is required to delete the remaining 2 elements).
  3. Remainder = 2: The total number of operations is the "quotient" of dividing the element by 3 plus 1 (the last two elements are deleted using one operation).

If any element appears only once, it cannot be deleted, and the function should return -1.

為了要最小化operations次數,我們要盡可能地刪除三個相同元素,也就是找出每個元素出現次數「除以 3 的餘數」,總共有以下三種可能:

  1. 餘 0: 總操作次數為該元素出現次數 除以3 的商
  2. 餘 1: 總操作次數為該元素出現次數 除以3 的商 + 1 次(把最後一次操作換成刪除兩個元素,再用一次操作把最後的兩個元素刪除)
  3. 餘 2: 總操作次數為該元素出現次數 除以3 的商 + 1 次(把最後的兩個元素刪除)

Approach

  1. Create a hash map to represent the frequency of each element
  2. Traverse the hash map, check if the count of each element is equal to 1. If so, return -1. Otherwise, check the result of count % 3, and record it in the final answer.

Complexity

Code

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        if len(nums) == 2:
            return 1 if nums[0] == nums[1] else -1

        # Build the has map
        counts = {}
        for n in nums:
            if n not in counts:
                counts[n] = 1
            else:
                counts[n] += 1

        operations = 0 

        for k, v in counts.items():
            if v == 1:
                return -1
            
            r = v % 3  # remainder
            q = v // 3 # quotient
            
            if r == 0:
                operations += q
            else:
                operations += q + 1
        
        return operations