LeetCode 2244: Minimum Rounds to Complete All Tasks
Problem Description
Explanation
To solve this problem, we can use a greedy approach. We need to find the minimum number of rounds required to complete all tasks. We can iterate through the tasks and group them by their difficulty level. Then, for each difficulty level group, we can calculate the number of rounds needed to complete all tasks in that group. If at any point we encounter a difficulty level group with more tasks than can be completed in 2 or 3 tasks per round, we return -1 as it is not possible to complete all the tasks.
Algorithm:
- Create a map to store the count of tasks for each difficulty level.
- Iterate through the tasks and populate the map.
- For each difficulty level group in the map, calculate the number of rounds needed to complete all tasks in that group.
- If the number of tasks in a group is not divisible by 2 or 3, return -1.
- Calculate the total rounds needed by summing the rounds needed for each group.
Time Complexity: The time complexity of this algorithm is O(n), where n is the number of tasks, as we iterate through the tasks only once.
Space Complexity: The space complexity is O(n) to store the count of tasks in the map.
Solutions
import java.util.HashMap;
import java.util.Map;
class Solution {
public int minRounds(int[] tasks) {
Map<Integer, Integer> taskCount = new HashMap<>();
for (int task : tasks) {
taskCount.put(task, taskCount.getOrDefault(task, 0) + 1);
}
int rounds = 0;
for (int count : taskCount.values()) {
if (count % 2 != 0 && count % 3 != 0) {
return -1;
}
rounds += (count + 1) / 2;
}
return rounds;
}
}
Loading editor...