DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

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 <= 105
  • 1 <= tasks[i] <= 109

SOLUTION:

from collections import Counter

class Solution:
    def minimumRounds(self, tasks: List[int]) -> int:
        rounds = 0
        ctr = Counter(tasks)
        for f in ctr.values():
            found = False
            for i in range(f // 3, -1, -1):
                if (f - 3 * i) % 2 == 0:
                    rounds += i + (f - 3 * i) // 2
                    found = True
                    break
            if not found:
                return -1
        return rounds
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay