Similar Problems

Similar Problems not available

Minimum Rounds To Complete All Tasks - Leetcode Solution

Companies:

LeetCode:  Minimum Rounds To Complete All Tasks Leetcode Solution

Difficulty: Medium

Topics: greedy hash-table array  

Problem Statement:

Given an array tasks representing the tasks that need to be done, where tasks[i] is the time it takes to complete the ith task. Also, there are n workers, where each worker can only complete one task at a time.

Return the minimum number of rounds to complete all the tasks.

The algorithm must satisfy the following conditions:

  1. Each worker can complete only one task at a time.
  2. Each worker finishes his assigned task before taking a new one.
  3. The assignment of tasks cannot be changed.

Solution:

To solve this problem, we can follow the following approach:

  1. First, we sort the array of tasks in descending order since we want to assign the largest tasks to the workers first. This will help us to minimize the number of rounds required to complete all tasks.
  2. We create an array of size n, where we store the time taken by each worker to complete their assigned task. Initially, all elements of the array will be set to 0 as no worker has been assigned any task yet.
  3. We loop through all tasks and assign each task to the worker who has the minimum time taken so far. We update the time taken by that worker to the sum of his current time and the time required to complete the task.
  4. Finally, the number of rounds required to complete all the tasks will be equal to the maximum time taken by any worker.

Here is the Python code implementing the above approach:

def minRoundstoCompleteAllTasks(tasks, n): tasks.sort(reverse = True) # Sorting tasks in descending order totalTimeTaken = [0] * n # Creating an array to store time taken by each worker for task in tasks: minTimeTaken = min(totalTimeTaken) # Finding the worker with minimum time taken so far totalTimeTaken[totalTimeTaken.index(minTimeTaken)] += task # Updating time taken by the worker return max(totalTimeTaken) # Returning the maximum time taken by any worker

Here, the time complexity of the solution is O(n log n), which is the time complexity of sorting the tasks array. The loop for assigning tasks will take O(N) time. Therefore, the overall time complexity of the solution is O(N log N).

Example:

tasks = [4, 3, 2, 6, 7, 2, 4]
n = 3
Output: 12

In this example, we have 7 tasks and 3 workers. These are the tasks assigned to workers in each round:

Round 1: worker 1 takes task 7 (time taken = 7)
Round 2: worker 2 takes task 6 (time taken = 6)
Round 3: worker 3 takes task 4 (time taken = 4)
Round 4: worker 1 takes task 4 (time taken = 11)
Round 5: worker 2 takes task 3 (time taken = 9)
Round 6: worker 3 takes task 2 (time taken = 6)
Round 7: worker 1 takes task 2 (time taken = 13)

Therefore, the total number of rounds required to complete all tasks is 7.

Minimum Rounds To Complete All Tasks Solution Code

1