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:
Return the minimum number of operations required to make the array empty, or -1 if it is not possible.
Example 1:
Input: nums = [2,3,3,2,2,4,2,3,4]
Output: 4Explanation: We can apply the following operations to make the array empty:
Example 2:
Input: nums = [2,1,2,2,3,3]
Output: -1Explanation: It is impossible to empty the array.
Constraints:
2 <= nums.length <= 100,0001 <= nums[i] <= 1,000,000class Solution:
def minOperations(self, nums: List[int]) -> int:
def dfs(cur):
if cur < 0:
return float('inf')
if cur == 0:
return 0
ops = min(dfs(cur - 2), dfs(cur - 3))
return 1 + ops
count = Counter(nums)
res = 0
for num, cnt in count.items():
op = dfs(cnt)
if op == float("inf"):
return -1
res += op
return resWhere is the size of the array and is the average frequency of the array elements.
class Solution:
def minOperations(self, nums: List[int]) -> int:
cache = {}
def dfs(num):
if num < 0:
return float("inf")
if num in [2, 3]:
return 1
if num in cache:
return cache[num]
res = min(dfs(num - 2), dfs(num - 3))
cache[num] = res + 1
return cache[num]
count = Counter(nums)
res = 0
for num, cnt in count.items():
op = dfs(cnt)
if op == float("inf"):
return -1
res += op
return resWhere is the size of the array and is the average frequency of the array elements.
class Solution:
def minOperations(self, nums: List[int]) -> int:
count = Counter(nums)
maxf = max(count.values())
minOps = [0] * (maxf + 1)
minOps[1] = float("inf")
for i in range(2, maxf + 1):
minOps[i] = minOps[i - 2]
if i - 3 >= 0:
minOps[i] = min(minOps[i], minOps[i - 3])
if minOps[i] != float("inf"):
minOps[i] += 1
res = 0
for num, cnt in count.items():
op = minOps[cnt]
if op == float("inf"):
return -1
res += op
return resWhere is the size of the array and is the average frequency of the array elements.
class Solution:
def minOperations(self, nums: List[int]) -> int:
count = Counter(nums)
res = 0
for num, cnt in count.items():
if cnt == 1:
return -1
res += math.ceil(cnt / 3)
return res