2244.Minimum Rounds to Complete All Tasks === ###### tags: `Medium`,`Array`,`Hash Table`,`Greedy`,`Counting` [2244. Minimum Rounds to Complete All Tasks](https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/) ### 題目描述 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^5^ * 1 <= `tasks[i]` <= 10^9^ ### 解答 #### Python ```python= class Solution: def minimumRounds(self, tasks: List[int]) -> int: counter = Counter(tasks) ans = 0 for cnt in counter.values(): if cnt < 2: return -1 else: ans += (cnt + 2) // 3 return ans ``` 寫到這靈感就來了 ```python= class Solution: def minimumRounds(self, tasks: List[int]) -> int: return -1 if 1 in Counter(tasks).values() else sum((cnt + 2) // 3 for cnt in Counter(tasks).values()) ``` > [name=Kobe][time=Jan 4, 2023] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)