Minimum Rounds to Complete All Tasks Problem
Description
LeetCode Problem 2244.
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.
Example 1:
Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2.
- In the second round, you complete 2 tasks of difficulty level 3.
- In the third round, you complete 3 tasks of difficulty level 4.
- In the fourth round, you complete 2 tasks of difficulty level 4.
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
Example 2:
Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
Constraints:
1 <= tasks.length <= 10^51 <= tasks[i] <= 10^9
Note: This question is the same as 2870: Minimum Number of Operations to Make Array Empty.
Solution
Approach: Hash Table
Tasks of the same difficulty are independent, so count how many tasks each difficulty has.
A difficulty with exactly one task can never be completed (a round takes 2 or 3 tasks), so return -1. For a count v of at least 2, the fewest rounds is ceil(v / 3): use groups of 3, and if 1 or 2 remain, one more round of 2 (borrowing from a group of 3 when 1 remains). Sum these over all difficulties.
Complexity: O(n) time and O(n) space.
class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
cnt = Counter(tasks)
ans = 0
for v in cnt.values():
if v == 1:
return -1
ans += v // 3 + (v % 3 != 0)
return ans